HarmonyOS for Android Developers — Part 2

My previous article about HarmonyOS and the importance of it can be checked here, I would suggest you go through this article before starting with this.

What does HarmonyOS have to offer for Android Developers?

· Devices use it only if it is necessary, like a modular operating system.

· The modularized decoupled HarmonyOS can be embedded in various devices according to the requirement.

· Adaptable to a wide variety of devices.

· A distributed app can be developed via the distributed capability kit in the same way a standalone app is created.

· Integrated development environment for multi-device development.

· Multiple languages will be supported by the compiler for unified development.

Ideally, all the devices connected to a user should be able to benefit from the connectivity capabilities of the hardware, regardless of where the software is installed.

HarmonyOS helps us to accomplish this goal by creating a fair ecosystem that is capable of full connectivity in any scenario and allows us to achieve a smart ecosystem.

Below list down some of the comparison between HarmonyOS and Android

What is the equivalent of a AndroidMainifest.xml file?

In Android, an AndroidMainifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc. It also includes information related to project such as App name, App Icon, App theme, Permission, app version, sdk version, etc.

<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.org.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" /></intent-filter>
</activity>
</application>
</manifest>

For same in HarmonyOS we have config.json file which contains information of your app, api version, module, device configuration, etc. also include information related to project such as App name, App Icon, Permission, etc. for more details check here.

{
"app": {
"bundleName": "com.org.example",
"vendor": "vendorName",
"version": {
"code": 1000000,
"name": "1.0.0"
},
"apiVersion": {
"compatible": 5,
"target": 5,
"releaseType": "Release"
}
},
"deviceConfig": {},
"module": {
"package": "com.org.example",
"name": ".MyApplication",
"reqPermissions": [
{
"name": "ohos.permission.VIBRATE",
"reason": "vibration",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
}
],
"deviceType": [
"phone"
],
"abilities": [
{
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"orientation": "unspecified",
"name": "com.org.example.MainAbility",
"icon": "$media:icon",
"description": "$string:mainability_description",
"label": "$string:app_name",
"type": "page",
"launchType": "standard"
}
]
}
}

As you have seen, both the files are containing all the details needed by the OS system about the application. But you have seen one major difference between this two files that is AndroidManifest.xml is in xml format and config.json is in json format. So below is some comparison between important elements

1. Versions details

In AndroidManifest.xml file, you have to put version details in <manifest> tag and sdk version put in <uses-sdk> tag.

<manifest 
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="30" />
</manifest>

In config.json file, you have to put version details in app object.

"app": {
"version": {
"code": 101,
"name": "1.0.0"
},
"apiVersion": {
"compatible": 5,
"target": 5,
"releaseType": "Release"
}
}

2. Package

In AndroidManifest.xml file, you have to put package name in root tag that is <manifest> tag.

<manifest
package="com.org.example">
...
</manifest>

In config.json file, you have to put package name in module object.

"module": {
"package": "com.orzangleli.radarview
}

3. Application details

In AndroidManifest.xml file, you have to put application details under < application> tag.

<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

</application>

In config.json file, you have to put application details in multiple object deviceConfig and module.

"deviceConfig": {
"default": {
"supportBackup": false,
"network": {
"cleartextTraffic": true,
"securityConfig": {
"domainSettings": {
"cleartextPermitted": true,
"domains": [
{
"subdomains": true,
"name": "example.ohos.com"
}
]
}
}
}
}
},
"module": {
"package": "com.orzangleli.radarview",
"name": ".MyApplication",
"deviceType": [
"phone"
],
"colorMode": "light"
}

4. Activities and Services

In AndroidManifest.xml file, you have to register Activities and Services under <application> tag with <activity> and <service> tag respective.

<application
android:icon="@drawable/app_icon"
android:label="@string/app_name" >
<activity
android:label="@string/activity_title"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:exported="true"
/>
</application>

In HarmonyOS, the equivalent of Activity and Service is Ability. So in config.json file you have to register all the abilities under module object as abilities json array. And you can set type(i.e. Page, Service) of ability using type attribute.

"module": {

"abilities": [
{
"name": ".MainAbility",
"description": "himusic main ability",
"icon": "$media:ic_launcher",
"label": "HiMusic",
"launchType": "standard",
"orientation": "unspecified",
"permissions": [
],
"visible": true,
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
]
}
],
"type": "page"
},
{
"name": ".MyService",
"description": "himusic play ability",
"icon": "$media:ic_launcher",
"label": "My Service",
"launchType": "standard",
"orientation": "unspecified",
"visible": false,
"skills": [
{
"actions": [
"action.play.music",
"action.stop.music"
],
"entities": [
"entity.audio"
]
}
],
"type": "service"
}
]
}

5. Permission

In AndroidManifest.xml file, you have add permission under < manifest > tag using < uses-permission> tag.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.org.example">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>



</manifest>

In config.json file, you have to add permission under module object as reqPermissions json array.

"module": {
"package": "com.org.example",
"name": ".MyApplication",
"reqPermissions": [
{
"name": "ohos.permission.READ_MEDIA",
"reason": "reading files",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "always"
}
},
{
"name": "ohos.permission.WRITE_MEDIA",
"reason": "writing files",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "always"
}
},
{
"name": "ohos.permission.INTERNET"
}
]
}

What is equivalent of Activities and it’s lifecycle?

In Android, an Activity represents a single focused screen with a user interface the user can do. In HarmonyOS you can used PageAbility for provide user interface. A Page ability may contain one ability slice or multiple ability slices that provide highly relevant capabilities.

public class MainAbility extends Ability {

@Override

public void onStart(Intent intent) {

super.onStart(intent);

super.setMainRoute(MainAbilitySlice.class.getName());

}

}

In Android, you can override methods from the Activity to capture lifecycle methods for the activity itself. In HarmonyOS, You can override methods from the Ability to capture lifecycle methods for the page ability. for more details about Page Ability and it’s lifecycle please check here.

Below image shows transitions between different lifecycle states of a Page ability and the callbacks to be invoked during the transitions.

Transitions between different states in a Page ability’s lifecycle

What is equivalent of Fragment and it’s lifecycle?

In Android, A Fragment is a piece of an activity which represents a behavior or a portion of user interface. Fragments are a way to modularize your code, compose sophisticated user interfaces for larger screens, and help scale your application UI. In HarmonyOS you have Fraction. A Fraction can be placed in a container (an Ability) as a part of its UI and cannot be used independently. for more details about Fraction and it’s lifecycle please check here.

In below example you can see extended Fraction class with all its lifecycle method overrided.

public class MyFraction extends Fraction {

@Override
protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
return super.onComponentAttached(scatter, container, intent);
}

@Override
protected void onStart(Intent intent) {
super.onStart(intent);
}

@Override
protected void onActive() {
super.onActive();
}

@Override
protected void onInactive() {
super.onInactive();
}

@Override
protected void onForeground(Intent intent) {
super.onForeground(intent);
}

@Override
protected void onBackground() {
super.onBackground();
}

@Override
protected void onStop() {
super.onStop();
}

@Override
protected void onComponentDetach() {
super.onComponentDetach();
}
}

What is equivalent of Services and it’s lifecycle?

In Android, A service is a component that runs in the background to perform long-running operations such as playing music, handle network transactions, interacting content providers etc. It doesn’t have any UI (user interface). In HarmonyOS you have Service Ability. A Service ability is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. for more details about Service Ability and it’s lifecycle please check here.

You can create service ability as follow.

public class ServiceAbility extends Ability {

@Override
public void onStart(Intent intent) {
super.onStart(intent);
}

@Override
public void onCommand(Intent intent, boolean restart, int startId) {
super.onCommand(intent, restart, startId);
}

@Override
public IRemoteObject onConnect(Intent intent) {
return super.onConnect(intent);
}

@Override
public void onDisconnect(Intent intent) {
super.onDisconnect(intent);
}

@Override
public void onStop() {
super.onStop();
}

}

Below image show Transitions between different states in a Service ability’s lifecycle.

Transitions between different states in a Service ability’s lifecycle

What is the equivalent of a LinearLayout?

In Android, a LinearLayout is used to lay your widgets out linearly — either horizontally or vertically. In HarmonyOS you have DirectionalLayout. Directional layout is used to arrange a group of components horizontally or vertically. For more details please check here.

In Android

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

In HarmonyOS

<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:orientation="vertical"
>

What is the equivalent of a RelativeLayout?

In Android, A RelativeLayout lays your widgets out relative to each other. In HarmonyOS you have DependentLayout. DependentLayout provides more layout modes. You can specify the position of each component relative to other components at the same level or the position relative to the parent component. For more details please check here.

<?xml version="1.0" encoding="utf-8"?><DependentLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_content"
ohos:height="match_content"
ohos:background_element="$graphic:color_light_gray_element">
<Text
ohos:id="$+id:text1"
ohos:width="match_content"
ohos:height="match_content"
ohos:left_margin="15vp"
ohos:top_margin="15vp"
ohos:bottom_margin="15vp"
ohos:text="text1"
ohos:text_size="20fp"
ohos:background_element="$graphic:color_cyan_element"/>
<Text
ohos:id="$+id:text2"
ohos:width="match_content"
ohos:height="match_content"
ohos:left_margin="15vp"
ohos:top_margin="15vp"
ohos:right_margin="15vp"
ohos:bottom_margin="15vp"
ohos:text="end_of text1"
ohos:text_size="20fp"
ohos:background_element="$graphic:color_cyan_element"
ohos:end_of="$id:text1"/>
</DependentLayout>

What is the equivalent of a View in HarmonyOS?

In Android, the View is the foundation of everything that shows up on the screen. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). In HarmonyOS you have Component class. Component occupies a rectangular area on the screen and is responsible for drawing and event processing in this area. For more details about Component please check here.

Below image showing View hierarchy (Android).

View hierarchy (Android)

Below image showing Component hierarchy (HMOS).

Component and ComponentContainer hierarchy (HarmonyOS)

What is the alternative of a basic UI components (i.e., TextView, EditText, ect) in HarmonyOS?

In Android, there are some pre-define widgets available for creating user interface such as TextView, EditText, Button, etc. In HarmonyOS also there are some pre-define component available in HMOS sdk.

Below is the list of alternative for android widgets.

1. TextView -> Text

In Android, TextView is a UI Component that displays the text to the user on their Display Screen. In HarmonyOS you can use Text. For more details check here.

<Text
ohos:id="$+id:text_welcome"
ohos:height="match_content"
ohos:width="match_content"
ohos:layout_alignment="horizontal_center"
ohos:text="welcome"
ohos:text_size="26fp"
/>

2. EditText -> TextField

In Android, EditText is a user interface control that allows the users to enter some text. In HarmonyOS you can use TextField. For more details check here.

<TextField
ohos:id="$+id:input_email"
ohos:height="match_content"
ohos:width="match_parent"
ohos:hint="Enter Email"
ohos:top_margin="8vp"
ohos:text_size="16fp"
ohos:padding="16vp"
ohos:background_element="$graphic:background_text_field"
ohos:text_input_type="pattern_text"
/>

3. Button -> Button

In Android, Button is a UI that is used to perform some action as soon as the user clicks on it. In HarmonyOS also have Button. For more details check here.

<Button
ohos:id="$+id:btn_login"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="Login"
ohos:layout_alignment="horizontal_center"
ohos:text_size="18fp"
ohos:start_padding="20vp"
ohos:end_padding="20vp"
ohos:top_padding="16vp"
ohos:bottom_padding="16vp"
/>

4. ImageView -> Image

In Android, ImageView is a view where you can show image. In HarmonyOS you have Image. For more details check here.

<Image
ohos:id="$+id:icon"
ohos:height="200vp"
ohos:width="200vp"
ohos:image_src="$media:profile_person"
ohos:scale_mode="clip_center"
/>

5. Seekbar -> Slider

In Android, Seekbar is an extended Progress bar. A Seekbar comes with a pointer that is draggable throughout the bar either in left or right. This pointer helps to set the progress as well. This helps the user to choose a particular range of values. In HarmonyOS you have Slider. For more details check here.

<Slider
ohos:id="$+id:slider"
ohos:width="match_content"
ohos:height="40vp"
ohos:max="4"
ohos:progress="4"
/>

6. CheckBox -> CheckBox

A CheckBox is the UI control that has two states that are either checked or unchecked. If we have a group of CheckBox, we can select as many as we want, unlike RadioGroup. In HarmonyOS also have CheckBox. For more details check here.

<Checkbox
ohos:height="match_content"
ohos:width="match_content"
ohos:text="Agree"
/>

7. Switch -> Switch

In Android, a switch is a two-state UI element that holds either ON or OFF state. ON generally means Yes and OFF means No. By default, a switch is in the OFF state. A user can change its state many times. In HarmonyOS also have Switch. For more details check here.

<Switch
ohos:height="match_content"
ohos:width="match_content"
ohos:text="Agree"
ohos:enabled="false"
/>

8. Progressbar -> Progressbar, RoundProgressbar

In Android, we have a progress bar that shows the progress of some action that is happening like pasting a file to some location. A progress bar can be in two modes: a) Determinate Mode, b) Indeterminate Mode.

In HarmonyOS, you have Progressbar and RoundProgressbar. For more details check here.

<ProgressBar
ohos:id="$+id:progressbar"
ohos:progress_width="10vp"
ohos:height="60vp"
ohos:width="600vp"
ohos:max="100"
ohos:min="0"
ohos:progress="60"
/>
<RoundProgressBar
ohos:id="$+id:round_progress_bar"
ohos:height="200vp"
ohos:width="200vp"
ohos:progress_width="10vp"
ohos:progress="20"
ohos:progress_color="#47CC47"
/>

9. Toast -> ToastDialog

In Andorid, Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after some time. In HarmonyOS you have ToastDialog. For more details check here.

new ToastDialog(getContext())
.setText("This is a ToastDialog displayed in the middle")
.setAlignment(LayoutAlignment.CENTER)
.show();

What is the equivalent of a Drawables in HarmonyOS?

In Android, A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon. There are several different types of drawables: such as Shape Drawable, Vector Drawable, Scale Drawable, ect.

In HarmonyOS you have Element. Element an abstract class of something that can be drawn. When static images need to be displayed in an application, this class and its child classes can be used to draw shapes and images. There are several subclasses which is used as per the type of Element such as ShapeElement, VectorElement, PixelMapElement. For more details check here.

How do I create notification in HarmonyOS?

In Android, A notification is a message you can display to the user outside of your application. you need to set the notification’s content and channel using a NotificationCompat.Builder object. Also it is compulsory from Android Oreo to create notification channel. And for showing notification you need NotificationManager object.

Same in HarmonyOS also we have notification for displaying message outside of application. To create notification in HarmonyOS you need NotificationRequest object to set notification’s content, slot(channel) and other details. In HarmonyOS equivalent of NotificationChannel is NotificationSlot. And with the help of NotificationHelper class you can publish your notification. For more details about notification check here.

//Create notification slot.
NotificationSlot notificationSlot = new NotificationSlot("notification_001", "low priority", NotificationSlot.LEVEL_LOW);
notificationSlot.setEnableVibration(true);
notificationSlot.setEnableLight(true);
try {
NotificationHelper.addNotificationSlot(notificationSlot);
} catch (RemoteException e) {
e.printStackTrace();
}

//Create notification.
NotificationRequest notificationRequest = new NotificationRequest();
NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
content.setTitle("Notification");
content.setText("Hi there");
NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
notificationRequest.setTapDismissed(true);
notificationRequest.setSlotId("notification_001");
notificationRequest.setContent(notificationContent);
notificationRequest.setIntentAgent(getLaunchAction());
try {
NotificationHelper.publishNotification(notificationRequest);
} catch (RemoteException e) {
e.printStackTrace();
}
// Create Intent agent.
private IntentAgent getLaunchAction() {
Operation operation = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName(this.getBundleName())
.withAbilityName("com.huawei.notification.SecondAbility")
.build();
Intent intent = new Intent();
intent.setOperation(operation);
List<Intent> intentList = new ArrayList<>();
intentList.add(intent);
List<IntentAgentConstant.Flags> flags = new ArrayList<>();
flags.add(IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG);
IntentAgentInfo paramsInfo = new IntentAgentInfo(90, IntentAgentConstant.OperationType.START_ABILITY, flags, intentList, null);
return IntentAgentHelper.getIntentAgent(this, paramsInfo);
}

How do I Add Animation on any component in HarmonyOS?

In Android, you either create animations using XML, or call the animate() method on a view. Also using ValueAnimator you have more control over animations and customize them at each step of execution.

In HarmonyOS, java sdk provides three major classes for animation: FrameAnimationElement, AnimatorValue, AnimatorProperty, and AnimatorGroup. For more details please check here.

What is the equivalent of local database(SQLite) in HarmonyOS?

In Android, for managing local data of application we have SQLite database and for small amount of data we have SharedPreference where we can store the data in the key-value pairs.

In HarmonyOS, the Object Relational Mapping (ORM) database is masks operations in structured query language (SQL) in the underlying SQLite database, and provides a series of object-oriented APIs for adding, deleting, modifying, and querying entities and relational data. The ORM is an abstraction layer above the SQLite database. For more details about ORM database please check here.

You can see the workflow of ORM database in below figure.

How the ORM database works

In HarmonyOS, the equivalent of SharedPreference is Lightweight Preference. In the Lightweight Preference you can store the data in the form of key-value pairs. For more details about Lightweight Preference please check here.

You can see the workflow of Lightweight Preference database in below figure.

Working Principles of Lightweight preference database
Example of Lightweight Preference database:Context context = getApplicationContext(); // Storage path of data files: /data/data/{PackageName}/preferences
DatabaseHelper databaseHelper = new DatabaseHelper(context);// The input parameter context is of the ohos.app.Context type.
String fileName = "test_pref"; // fileName indicates the file name, which cannot be empty or contain a path. The default path can be obtained by calling context.getPreferencesDir().
Preferences preferences = databaseHelper.getPreferences(fileName);

//Read data
int value = preferences.getInt("intKey", 0);

//Write data
preferences.putInt("intKey", 3);
preferences.putString("StringKey", "String value");
preferences.flush();

--

--

Application Library Engineering Group
Application-Library-Engineering-Group

World’s Innovative open collaborate Platform, build reusable application components to reduce effort and fast track application development on multiplatform.