鸿蒙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声明式范式。实际开发中优先使用第一种直接获取方式,其代码简洁且符合最新规范。

相关推荐
游戏技术分享8 小时前
【鸿蒙游戏技术分享 第75期】AGC后台批量导入商品失败,提示“参数错误”
游戏·华为·harmonyos
No Silver Bullet9 小时前
HarmonyOS NEXT开发进阶(十七):WebView 拉起 H5 页面
华为·harmonyos
liuhaikang9 小时前
【鸿蒙HarmonyOS Next App实战开发】口语小搭档——应用技术实践
harmonyos
北方的流星11 小时前
华为交换机MSTP和VRRP综合应用配置
运维·网络·华为
C雨后彩虹12 小时前
简易内存池
java·数据结构·算法·华为·面试
liuhaikang12 小时前
鸿蒙VR视频播放库——md360player
音视频·vr·harmonyos
北方的流星14 小时前
华为交换机IPv6静态路由、默认路由、RIPng和OSPFv3路由配置
运维·网络·华为
飞露14 小时前
鸿蒙Preview预览文件失败原因
华为·harmonyos
夏小鱼的blog15 小时前
【HarmonyOS应用开发入门】第五期:状态管理V2入门 - 1
harmonyos·状态管理
小雨青年15 小时前
鸿蒙 HarmonyOS 6 | ArkUI (04):数据展示 List 列表容器 LazyForEach 懒加载机制
华为·list·harmonyos