Based on distributed soft bus, distributed data management, distributed Profile and other technical features, Hongmun distributed task scheduling builds a unified distributed service management (discovery, synchronization, registration, invocation) mechanism, supporting remote startup, remote invocation, remote connection, migration and other operations for cross-device applications. Select appropriate devices to run distributed tasks based on the capabilities, locations, service running status, resource usage, and user habits and intentions of different devices. This paper will build the first hongmeng application with distributed task scheduling application migration.

Results the preview

The demo results are as follows:When running on a phone, the image above is arranged vertically. Click the button on the right of application Migration in the picture, the permission application pop-up box will appear:If the user has the same application installed on the mobile phone, and multiple devices are allowed to access the application, and the device verification is the same user, the application on the mobile phone will be migrated to the TV. The mobile effect picture is not provided because there is no mobile phone that supports Hongmeng at present, and individual developers cannot apply for Profile file and type. App package, so the effect picture cannot be provided.

The development of

  1. Development tools.

Hongmeng Application development has a special IDE, and HUAWEI DevEco Studio 2.0.10.201 is used for the development of this paper. If you have not installed it, please visitDownload and install from official website. DevEco, like Android Studio, is based on the IntelliJPlatform, and there’s not much difference between the two, making it seamless for Android developers to use. Check the configuration of the development environmentThe official guide. 2. Create projects. Open DevEco Studio, click File– >New– >New Project, and the following options appear:When creating a new project, there are a variety of device choices and development framework (Java, JS) choices. In this paper, TV and Empty Feature Ability(Java) are selected because the large screen display effect is better and Java development is more familiar. There are currently no phones available as there are currently no phones available for individual developers to use with The Hongmeng system, which is expected in the near future. After the new project is created, the following project configuration will appear:The directory structure of the project is basically the same as that of Android Studio, where entry>libs: used to store the dependency files of the Entry module, Entry > SRC >main>Java: used to store the Java source code, entry> SRC >main>resources: Used to store resource files used by applications, such as graphics, multimedia, strings, and layout files:

The resource directory Resource File Description
base>element Json files containing strings, integers, colors, styles, and other resources.
base>graphic Scalable Vector Graphics (SVG) Scalable Vector Graphics files, basic geometric shapes (rectangles, circles, lines, etc.) Shape resources, etc.
base>layout Interface layout file in XML format.
base>media Multimedia files, such as graphics, videos, and audio files, can be in. PNG,. GIF,. Mp3, and. Mp4 formats
rawfile Used to store raw resource files in any format. Rawfile does not match different resources based on device status. You need to specify the file path and file name for reference.

Some resource directories are not created in the figure above. Developers can create them by themselves when they need to use them. For details, see HommnyOS Project Introduction. MainAbility in the figure is equivalent to Android MainActivity.

  1. Create a view (UI).

Views are created in the same way as Android, with support for both code and XML creation. This article uses XML creation:


      
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical">
    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:orientation="horizontal">
        <Text
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:layout_alignment="center"
            ohos:text="Application Migration"
            ohos:text_color="# 000000"
            ohos:text_size="48px"/>
        <Image
            ohos:id="$+id:ig_sync"
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:image_src="$media:case"
            ohos:left_margin="20px"/>
    </DirectionalLayout>
    <AdaptiveBoxLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:top_margin="20px">
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:orientation="vertical"
            ohos:margin="20vp">
            <Image
                ohos:id="$+id:dl_test0"
                ohos:height="match_content"
                ohos:width="match_content"
                ohos:image_src="$media:phone"/>
        </DirectionalLayout>
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:orientation="vertical"
            ohos:margin="20vp">
            <Image
                ohos:id="$+id:dl_test1"
                ohos:height="match_content"
                ohos:width="match_content"
                ohos:image_src="$media:tv"/>
        </DirectionalLayout>
    </AdaptiveBoxLayout>
</DirectionalLayout>
Copy the code

DirectionalLayout is equivalent to the Android LinearLayout, which is smooth and vertical. This paper chooses the vertical layout. AdaptiveBoxLayout is an adaptive layout that displays vertically on a device with a portrait screen or horizontally on a widescreen device. The use of other elements is roughly the same, including id declaration and the use of units need to pay attention to, VP is similar to Android DP, other attributes need developers to check the source code, you can also see the official development instructions. DevEco Studio had planned to provide instant preview (Java and JS) in the 2020-10-30 release, but somehow it wasn’t seen in the latest release.

  1. Function implementation.

Inject views into MainAbility:

public class MainAbility extends Ability implements IAbilityContinuation.Component.ClickedListener.Component.KeyEventListener {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        // super.setMainRoute(MainAbilitySlice.class.getName());
        super.setUIContent(ResourceTable.Layout_ability_main);

        Image sync = (Image) findComponentById(com.example.tvtest.ResourceTable.Id_ig_sync);
        sync.setClickedListener(this::onClick);
        sync.setKeyEventListener(this::onKeyEvent);

        Image test0 = (Image) findComponentById(com.example.tvtest.ResourceTable.Id_dl_test0);
        test0.setScaleMode(Image.ScaleMode.ZOOM_CENTER);

        Image test1 = (Image) findComponentById(com.example.tvtest.ResourceTable.Id_dl_test1);
        test1.setScaleMode(Image.ScaleMode.ZOOM_CENTER);

    }
Copy the code

SetMainRoute is a route to set the main page. MainAbilitySlice is a Fragment. Super. SetMainRoute (MainAbilitySlice. Class. GetName (), the result of the execution is to enter directly into MainAbilitySlice after application, this article page simple directly related in MainAbility processing logic. Because the Image resources are large, use setScaleMode(image.scalemode.zoom_center) to set the zoom of the Image in the center. Otherwise, the TV screen cannot display all the images. SetUIContent binds ability_main to MainAbility. FindComponentById is equivalent to findViewById.

  • Mobile phone Click event

After the sync is application migration button, click will be applied in the mobile phone data migration to the TV, so you need to implement Component. ClickedListener interface:

    /** * click event *@param component
     */
    @Override
    public void onClick(Component component) {
        switch (component.getId()){
            case com.example.tvtest.ResourceTable.Id_ig_sync:
                migrateAbility();
                break;
            default:
                break; }}Copy the code

If there is only one click event, you can get the click button without component.getid ().

  • TV click event

Because the code also runs on TVS, which don’t have a touch screen and aren’t as convenient as phones. TV control generally use the remote control, so developers need to monitor the TV remote button click event, need MainAbility implementation Component. KeyEventListener interface:

    /** * The migration starts when the center button of the remote control is pressed@param component
     * @param keyEvent
     * @return* /
    @Override
    public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
        if (keyEvent.isKeyDown() && keyEvent.getKeyCode() == KeyEvent.KEY_DPAD_DOWN) {
            migrateAbility();
            return true;
        }
        return false;
    }

Copy the code

Keyevent.iskeydown () && keyevent.getKeyCode () == keyevent.key_dPAD_down is the button press event and the center button of the remote control.

  • Permission verification and application

Click apply migration button and execute migrateAbility method to start migrating data. Before migrating, verify permissions:

 /** * application migration */
    private void migrateAbility(a) {
        if (verifySelfPermission(SystemPermission.DISTRIBUTED_DATASYNC) == IBundleManager.PERMISSION_GRANTED) {
            this.continueAbility();
        } else{ requestPermission(SystemPermission.DISTRIBUTED_DATASYNC); }}Copy the code

If you do not have corresponding permissions, you need to apply for the following permissions:

    /** * Apply for permission **@param permission
     */
    private void requestPermission(String permission) {
        if (canRequestPermission(permission)) {
            requestPermissionsFromUser(new String[]{permission}, 0x1001); }}Copy the code

Permission application result processing:


    /** * Permission application result **@param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || permissions.length == 0 || grantResults == null || grantResults.length == 0) {
            return;
        }
        if (requestCode == 0x1001 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
            this.continueAbility(); }}Copy the code

0 x1001: permission statement code, SystemPermission DISTRIBUTED_DATASYNC: application migration authority. Before application migration, you need to apply for the DISTRIBUTED_DATASYNC permission dynamically and in the config.json file:

{
  "app": {
    "bundleName": "com.example.tvtest"."vendor": "example"."version": {
      "code": 1."name": "1.0"
    },
    "apiVersion": {
      "compatible": 3."target": 3}},"deviceConfig": {},
  "module": {
    "package": "com.example.tvtest"."name": ".tvtest"."reqCapabilities": [
      "video_support"]."deviceType": [
      "tv"]."distro": {... },"abilities": [...]. ."reqPermissions": [{"name": "ohos.permission.DISTRIBUTED_DATASYNC"}}}]Copy the code

The reqPermissions position needs to be at the same level as Abilities. DeviceType declares that the current application is applicable to the TV terminal. Config. json is equivalent to androidmanifest.xml, but developers do not know how to configure it for the first time. It is not as clear as AndroidManifest.

  • Application migration

Application migration requires implementing the IAbilityContinuation interface:

public class MainAbility extends Ability implements IAbilityContinuation.Copy the code

Enforce overriding the following methods after implementing the IAbilityContinuation interface:

    @Override
    public boolean onStartContinuation(a) {
        return true;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        return true;
    }

    @Override
    public void onCompleteContinuation(int i) {
        this.terminateAbility();
    }
Copy the code

The default return value is false and the developer needs to change it to true. The continuability () method is unavailable without the IAbilityContinuation interface and cannot be migrated without calling it. OnSaveData () returns true to open the same state when the application is migrated to another device.

instructions

  • Currently, Hongmeng application is only for Hongmeng devices, and debugging only provides simulator debugging, which requires developers to log in and apply for.
  • Application migration must be performed by the same user on different devices; otherwise, application migration fails.
  • Individual developers cannot apply for some signature files, so the app cannot be packaged in. App format, so mobile renderings cannot be provided.
  • Some methods are still being explored and cannot be analyzed in detail.
  • A single set of code can run on multiple devices without special processing.
  • For infringement or error, please send an email to [email protected].