华为Harmony鸿蒙开发笔记三:PageAbility跨设备迁移

由于没有设备,模拟器又不支持启动多个,所以该功能没有实践,只贴代码,以后有机会再更新。

跨设备迁移,就是讲一个Ability(页面),从A设备,显示到B设备上的功能。

首先,讲需要迁移的Ability和它包含的Slice都实现IAbilityContinuation接口,并实现该接口的所有方法

package com.example.continuationdemo.slice;

import com.example.continuationdemo.MyApplication;
import com.example.continuationdemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

public class MainAbilitySlice extends AbilitySlice implements IAbilityContinuation {
    static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        Button btnStartAbility= (Button) findComponentById(ResourceTable.Id_btn_start_ability);
        if (btnStartAbility != null) {
            // 为按钮设置点击回调
            btnStartAbility.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    try {
                        continueAbility();
                        //请求迁移后,调用该页面的onStartContinuation()方法
                    } catch (IllegalStateException e) {
                        // Maybe another continuation in progress.
                    }
                }
            });
        }
    }


    @Override
    public boolean onStartContinuation() {
        //该方法在源设备执行
        //Page请求迁移后,系统首先回调此方法,开发者可以在此回调中决策当前是否可以执行迁移,比如,弹框让用户确认是否开始迁移。
        //返回true,表示可以迁移,执行onSaveData()方法
        return false;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {
        //该方法在源设备执行
        //如果onStartContinuation()返回true,则系统回调此方法,开发者在此回调中保存必须传递到另外设备上以便恢复Page状态的数据。
        //返回true表示保存数据成功
        return false;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        //该方法在目标设备执行
        //源侧设备上Page完成保存数据后,系统在目标侧设备上回调此方法,开发者在此回调中接受用于恢复Page状态的数据。
        // 注意,在目标侧设备上的Page会重新启动其生命周期,无论其启动模式如何配置。且系统回调此方法的时机在onStart()之前。
        return false;
    }

    @Override
    public void onCompleteContinuation(int i) {
        //该方法在源设备执行
          //目标设备上执行完onRestoreData方法以后,回调该方法,通知迁移成功
    }
}

 

上一篇:鸿蒙内核源码分析(调度队列篇) | 为什么只有就绪状态才有队列 ? | 百篇博客分析HarmonyOS源码 | v6.04


下一篇:codeforce610C. Harmony Analysi