美文网首页
ArkTS创建多个Ability常见问题

ArkTS创建多个Ability常见问题

作者: zaq1125 | 来源:发表于2024-07-18 09:38 被阅读0次

    1.先来创建流程总结

    //1.1获取上下文
    private context = getContext(this) as common.UIAbilityContext
    
    //1.2指定要跳转到的UIAbility的信息
    let want: Want = {
                  deviceId: '',
                  bundleName: 'com.example.myapplication',
                  moduleName: 'entry',
                  abilityName: 'DocumentAbility',
                  parameters: {
                    instanceKey: 'idx_' + this.index++
                  }
                }
    
    //1.3尝试拉起目标UIAbility实例
    this.context.startAbility(want)
    
    //2.在AbilityStage的生命周期回调中为目标UIAbility实例生成key
    export default class MyAbilityStage extends AbilityStage {
      onAcceptWant(want: Want): string {
        if(want.abilityName === 'DocumentAbility'){
          return `DocAbilityInstance_${want.parameters.instanceKey}`
        }
        return ''
      }
    }
    
    //3.在module.json5配置文件中,通过srcEntry参数指定AbilityStage路径
    {
      "module": {
        "name": "entry",
        "type": "entry",
        "srcEntry": './ets/myabilitystage/MyAbilityStage.ts',
         ...
      }
    }
    

    除了上述几个步骤外,还需要在module.json5配置文件中,通过launchType配置DocumentAbility的启动模式,如specified

      {
            "name": "DocumentAbility",
            "srcEntry": "./ets/documentability/DocumentAbility.ts",
            "description": "$string:DocumentAbility_desc",
            "icon": "$media:icon",
            "label": "$string:DocumentAbility_label",
            "startWindowIcon": "$media:icon",
            "startWindowBackground": "$color:start_window_background",
            "launchType": "specified"
          }
    

    另外,在DocumentAbility的onWindowStageCreate修改需要加载的入口界面,将DocumentPage(默认是Index)替换成你要加载的界面。

      onWindowStageCreate(windowStage: window.WindowStage) {
        // Main window is created, set main page for this ability
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    
        windowStage.loadContent('pages/DocumentPage', (err, data) => {
          if (err.code) {
            hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
            return;
          }
          hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
        });
      }
    

    相关文章

      网友评论

          本文标题:ArkTS创建多个Ability常见问题

          本文链接:https://www.haomeiwen.com/subject/mcsrhjtx.html