First experience of Hongmeng development (a must-see for Android development)

Author: pig intestine sad

On September 10, 2020, the HarmonyOS 2.0 system was officially released.

Hongmeng 2.0 releases a Beta version for application developers. It will release a large-screen, watch, and car version of Hongmeng on September 10, 2020, and a mobile version of Hongmeng in December 2020.

On September 10, 2020, the Hongmeng open source roadmap will target memory 128KB-128MB terminal devices; in October 2021, it will target all devices above 4GB.

background

As an Android developer, I am really excited to see the release of the domestically produced operating system. I am so excited that I want to see what is going on.

First open the official website and look at the definition of the system on the official website:

HarmonyOS is a "future-oriented" distributed operating system for all scenarios (mobile office, sports health, social communication, media entertainment, etc.). Based on the traditional single-device system capabilities, HarmonyOS proposes a distributed concept based on the same set of system capabilities and adapting to multiple terminal forms, which can support multiple terminal devices.

For application developers, HarmonyOS uses a variety of distributed technologies to enable application development to be independent of the morphological differences of different terminal devices, reducing development difficulty and cost. **This allows developers to focus on the upper-level business logic and develop applications more conveniently and efficiently. This advantage has a huge advantage in the era of 5G, the Internet of Everything.

Install DevEco Studio

Next, download DevEco Studio (IDE/Development Tools) to experience software development. Here you can see that the current IDE is only for Windows system (windows 10 64 bit). Gradle installation may fail during the installation process, remember To add a proxy, create a gradle.properties file in the user directory (open "this computer", enter **%userprofile%** in the folder address bar to enter the personal data interface.), add the file, and the port is the port of the proxy

systemProp.https.proxyPort=63729
systemProp.http.proxyHost=127.0.0.1
systemProp.https.proxyHost=127.0.0.1
systemProp.http.proxyPort=63729

The gradle installation is successful, but the build may fail during the compilation process. The error is as follows:

ERROR: Cause: mirrors.huaweicloud.com:443 failed to respond

The solution is to turn off all agents first, and then you will find silky smooth.

After installing DevEco Studio, you can see that the interface is very similar to Android Studio after opening

1. Layout development

Everything looks very familiar, it can be developed in languages ​​such as Java or JS , the layout can be created through XML, and the size unit is vp

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical"
    ohos:padding="32">
    <Text
        ohos:id="$+id:text"
        ohos:width="match_content"
        ohos:height="match_content"
        ohos:layout_alignment="horizontal_center"
        ohos:text="My name is Jackie."
        ohos:text_size="25vp"/>
    <Button
        ohos:id="$+id:button"
        ohos:width="match_content"
        ohos:height="match_content"
        ohos:layout_alignment="horizontal_center"
        ohos:text="My name is Jackie."
        ohos:text_size="50"/>
</DirectionalLayout>

It can also be created directly by Java code, click events are so kind

@Override
public void onStart(Intent intent) {
    super.onStart(intent);
    // 步骤1 声明布局
    DirectionalLayout directionalLayout = new DirectionalLayout(context);
    // 步骤2 设置布局大小
    directionalLayout.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
    directionalLayout.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
    // 步骤3 设置布局属性及ID(ID视需要设置即可)
    directionalLayout.setOrientation(Component.VERTICAL);
    directionalLayout.setPadding(32, 32, 32, 32);

    Text text = new Text(context);
    text.setText("My name is Text.");
    text.setTextSize(50);
    text.setId(100);
    // 步骤4.1 为组件添加对应布局的布局属性
    DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(LayoutConfig.MATCH_CONTENT,
        LayoutConfig.MATCH_CONTENT);
    layoutConfig.alignment = LayoutAlignment.HORIZONTAL_CENTER;
    text.setLayoutConfig(layoutConfig);

    // 步骤4.2 将Text添加到布局中
    directionalLayout.addComponent(text);

    // 类似的添加一个Button
    Button button = new Button(context);
    layoutConfig.setMargins(0, 50, 0, 0);
    button.setLayoutConfig(layoutConfig);
    button.setText("My name is Jackie.");
    button.setTextSize(50);
    button.setId(100);
    ShapeElement background = new ShapeElement();
    background.setRgbColor(new RgbColor(0, 125, 255));
    background.setCornerRadius(25);
    button.setBackground(background);
    button.setPadding(10, 10, 10, 10);
    button.setClickedListener(new Component.ClickedListener() {
        @Override
        // 在组件中增加对点击事件的检测
        public void onClick(Component Component) {
            // 此处添加按钮被点击需要执行的操作
        }
    });
    directionalLayout.addComponent(button);

    // 步骤5 将布局作为根布局添加到视图树中
    super.setUIContent(directionalLayout);
}

The layout of the home page is as follows, created by Java code

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        System.out.println("onStart");
        LayoutConfig config = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT);
        myLayout.setLayoutConfig(config);
        ShapeElement element = new ShapeElement();
        element.setRgbColor(new RgbColor(255, 255, 255));
        myLayout.setBackground(element);

        Text text = new Text(this);
        text.setLayoutConfig(config);
        text.setText("CT Jackie");
        text.setTextColor(new Color(0xFF000000));
        text.setTextSize(50);
        text.setTextAlignment(TextAlignment.CENTER);
        myLayout.addComponent(text);
        super.setUIContent(myLayout);
    }

The effect is as follows:

2. Life cycle

Let’s take a look at the life cycle of the main interface. The ILifecycle interface is implemented. There are seven life cycle states.

public static enum Event {
        UNDEFINED,
        ON_START,
        ON_INACTIVE,
        ON_ACTIVE,
        ON_BACKGROUND,
        ON_FOREGROUND,
        ON_STOP;
        private Event() {
        }
    }

OnStart() and onActive() are called when the interface starts

2020-09-13 21:42:10.266 25547-25547[表情] I/System.out: onStart
2020-09-13 21:42:10.284 25547-25547[表情] I/System.out: onActive

Called when the back button is clicked

2020-09-13 21:42:35.847 25547-25547/com.example.helloworld I/System.out: onInactive
2020-09-13 21:42:35.917 25547-25547/com.example.helloworld I/System.out: onBackground
2020-09-13 21:42:35.920 25547-25547/com.example.helloworld I/System.out: onStop

As for UNDEFINED and ON_FOREGROUND, I don’t know yet.

3.Gradle task (Task)

Even gradle's Task is very similar, the packaging command is assembleDebug/Release

> Task :entry:preBuild
> Task :entry:compileDebugNativeWithCmake
> Task :entry:collectDebugDependencies
> Task :entry:mergeDebugResources
> Task :entry:mergeDebugProfile
> Task :entry:compileDebugResources
> Task :entry:compileDebugIdl
> Task :entry:compileDebugRFile
> Task :entry:processDebugJavaResource
> Task :entry:compileDebugJavaWithJavac
> Task :entry:mergeDebugJavaResource
> Task :entry:generateDebugClassesJar
> Task :entry:mergeDebugProjectDex
> Task :entry:generateDebugShell
> Task :entry:processDebugShellManifest
> Task :entry:compileDebugShellResources
> Task :entry:linkDebugShellResources
> Task :entry:compileDebugShellJavaWithJavac
> Task :entry:mergeDebugShellDex
> Task :entry:packageDebugShell
> Task :entry:packageDebugSimplifyShell
> Task :entry:validateDebugSigning
> Task :entry:signDebugShell
> Task :entry:packageDebugHap
> Task :entry:signDebugHap
> Task :entry:assembleDebug

4. Configuration file

The configuration file is a file named config.json that configures some information about the application

{
  "app": {
    "bundleName": "com.example.helloworld",
    "vendor": "example",
    "version": {
      "code": 1,
      "name": "1.0"
    },
    "apiVersion": {
      "compatible": 3,
      "target": 3
    }
  },
  "deviceConfig": {
    "default": {

    }
  },
  "module": {
    "package": "com.example.helloworld",
    "name": ".HelloWorld",
    "reqCapabilities": [
      "video_support"
    ],
    "deviceType": [
      "wearable"
    ],
    "distro": {
      "deliveryWithInstall": true,
      "moduleName": "entry",
      "moduleType": "entry"
    },
    "abilities": [
      {
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ],
        "orientation": "landscape",
        "formEnabled": false,
        "name": "com.example.helloworld.MainAbility",
        "icon": "$media:icon",
        "description": "$string:mainability_description",
        "label": "HelloWorld",
        "type": "page",
        "launchType": "standard"
      }
    ]
  }
}

Looking carefully at this file, you will feel more and more that this is the json translation version of AndroidManifest.xml.

View Hongmeng from Decompilation Perspective

Since it looks so much like Android, it seems to me to see what is the product of its compilation. Is it possible to decompile the dex file like Android?

What you get after compilation is a xxx.hap file

Modify its suffix to .zip. After decompression, you can see that there are familiar assets, dex, apk files, etc. After installing this apk file, it is found that it cannot be used.

Next, we first decompile this classes.dex file. An error occurs after the first dex is decompiled.

~/Desktop/fanbianyi/dex2jar-2.0 » sh d2j-dex2jar.sh classes3.dex
dex2jar classes3.dex -> ./classes3-dex2jar.jar
com.googlecode.d2j.DexException: not support version.
    at com.googlecode.d2j.reader.DexFileReader.<init>(DexFileReader.java:151)
    at com.googlecode.d2j.reader.DexFileReader.<init>(DexFileReader.java:211)
    at com.googlecode.dex2jar.tools.Dex2jarCmd.doCommandLine(Dex2jarCmd.java:104)
    at com.googlecode.dex2jar.tools.BaseCmd.doMain(BaseCmd.java:288)

The reason is that our tool version is too low. Here is the solution. After the upgraded version is successfully decompiled, it will be classes3-dex2jar.jar. Open it and you can see

There is an additional ResourceTable file, which is our resource id table. The dex file here contains the code we developed.

Next, let’s decompile the apk file. After decompression, you can see that it contains familiar content.

The AndroidManifest.xml file is as follows

Decompile the dex file, you can see that MainAbilityShellActivity finally inherits AbilityShellActivity

ShellHelloWorld is actually an Application

At this point, I feel that the .hap file is like a package for the apk, and the final logic seems to be the android set. In other words, android developers will get started very quickly, and it may also be a preparation for future compatibility with the android system.

Distributed, cross-device migration

Migrate across devices

Let’s take a look at some of the highlights of the system, such as cross-device migration, which sounds like a very cool feature, such as directly migrating your phone screen to a computer or pad and performing some operations, etc.

Cross-device migration (hereinafter referred to as "migration")** supports the migration of Page between different devices of the same user in order to support the user's demand for seamless switching. **Taking Page migrated from device A to device B as an example, the main steps of the migration are as follows:

  1. Page on device A requests migration.
  2. HarmonyOS processes the migration task and calls back the data saving method of Page on device A to save the data necessary for migration.
  3. HarmonyOS starts the same Page on device B and calls back its data recovery method.

Developers can refer to the following detailed steps to develop Page with migration function.

Distributed task scheduling

In HarmonyOS, the distributed task scheduling platform provides unified component management capabilities for the **"super virtual terminal"** built by multiple devices equipped with HarmonyOS, and defines a unified capability baseline, interface form, data structure, and service description language for applications , Shielding hardware differences; supporting distributed tasks such as remote startup, remote invocation, and seamless business migration.

Distributed task scheduling platform realizes Ability at the bottom

  • Startup and shutdown: Provide developers with the ability to manage remote capabilities, that is, the ability to start Page templates, and the ability to start and close Service and Data templates.
  • Connection and disconnection: Provide developers with the ability to control services across devices (Ability of Service and Data templates). Developers can obtain or log off cross-device management service objects by connecting and disconnecting with remote services to achieve and Locally consistent service scheduling.
  • Migration capabilities: Provide developers with seamless migration capabilities across devices. Developers can seamlessly migrate local services to designated devices by calling the migration interface of the Page template Ability to break through the barriers between devices.

to sum up

Personally, the development of Hongmeng is very close to the habits of Android developers, and it is very easy to use for Android developers.

However, Android's existing multi-device collaboration support is very poor. Hongmeng has made some encapsulation and expansion to shield the underlying differences. In the era of multi-device and interconnection of all things, it has great advantages. The more devices cooperate, the more Hongmeng has Advantage.

Finally, I will share a copy of Hongmeng learning syllabus and Android learning PDF + architecture video + source code notes collected by the big guys , advanced architecture technology advanced mind map, Android development interview special materials, advanced advanced architecture materials

These are the fine materials that I will read again and again in my spare time. There are detailed explanations on the high-frequency knowledge points of interviews with major factories in recent years. I believe it can effectively help everyone master knowledge and understand principles.

Of course, you can also use it to check for omissions and improve your competitiveness.

I believe it will bring you a lot of gains. If you need it, you can click to get it !

If you like this article, you might as well give me a like, leave a message in the comment area, or forward and support it~

Guess you like

Origin blog.csdn.net/ajsliu1233/article/details/108664762