鸿蒙getContext(this)弃用后的替代方法

一、直接获取UIAbilityContext(推荐)

核心方法getUIContext().getHostContext()

特点

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

示例代码

TypeScript 复制代码
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参数 */ });
        })
    }
  }
}

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

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

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

三、特殊场景适配

Worker线程获取

需通过可发送对象转换:

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

API 19以下兼容方案

通过WindowStage间接获取:

TypeScript 复制代码
windowStage.getMainWindow().then(win => {
  const ctx = win.getUIContext().getHostContext();
});

⚠️ 注意事项

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

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

相关推荐
以太浮标17 小时前
华为eNSP模拟器综合实验之- ACL控制列表核心命令全解析及场景应用
运维·网络·网络协议·华为·信息与通信
特立独行的猫a18 小时前
CMake与GN构建系统对比及GN使用指南
harmonyos·cmake·openharmony·构建·gn
SuperHeroWu71 天前
如何判断应用在鸿蒙卓易通或者出境易环境下?
华为·harmonyos
大雷神1 天前
HarmonyOS APP<玩转React>开源教程十五:首页完整实现
react.js·开源·harmonyos
云和数据.ChenGuang1 天前
鸿蒙智联,极智共生:HarmonyOS与MiniMax智能体的融合新纪元
华为·harmonyos·鸿蒙
不爱吃糖的程序媛1 天前
已有 Flutter 应用适配鸿蒙平台指导文档
flutter·华为·harmonyos
大雷神1 天前
HarmonyOS APP<玩转React>开源教程十六:课程列表页面
harmonyos
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-video — 视频播放组件
react native·音视频·harmonyos
坚果派·白晓明1 天前
在 Ubuntu 中搭建鸿蒙 PC 三方库交叉编译构建开发环境
ubuntu·华为·harmonyos
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-webview — 网页渲染组件
react native·react.js·harmonyos