一、直接获取UIAbilityContext(推荐)

核心方法getUIContext().getHostContext()

特点

  • 从API 12+开始支持,是废弃getContext()后的官方替代方案
  • 返回UIAbilityContext类型对象,可直接操作Ability生命周期

示例代码

import { common } from '@kit.AbilityKit';

@Entry
@Component
struct MyPage {
  // 定义上下文变量
  private context: common.UIAbilityContext = 
      this.getUIContext().getHostContext() as common.UIAbilityContext;

  build() {
    Column() {
      Button("启动Ability")
        .onClick(() => {
          // 使用上下文启动新Ability
          this.context.startAbility({ /* Want参数 */ });
        })
    }
  }
}

二、通过全局存储传递适用场景:跨页面/非组件环境使用

1、在UIAbility中存储:
// EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage) {
  AppStorage.setOrCreate("uiContext", this.context); 
}

2、在Page中获取:
@StorageLink('uiContext') context: common.UIAbilityContext;

三、特殊场景适配

Worker线程获取
需通过可发送对象转换:

import { sendableContextManager } from '@kit.AbilityKit';
const sendableCtx = sendableContextManager.convertFromContext(context);
workerPort.postMessageWithSharedSendable(sendableCtx);

API 19以下兼容方案
通过WindowStage间接获取:

windowStage.getMainWindow().then(win => {
  const ctx = win.getUIContext().getHostContext();
});

⚠️ 注意事项

  1. 废弃接口:避免使用getContext()(API 18+已废弃)
  2. 类型断言:必须使用as common.UIAbilityContext明确类型
  3. 作用域限制:构造函数中无法获取,需在build()或事件回调中使用
  4. 线程安全:跨线程传递需使用sendableContextManager转换

以上方法均基于鸿蒙API 12+的ArkUI声明式范式。实际开发中优先使用第一种直接获取方式,其代码简洁且符合最新规范。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐