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

相关推荐
大雷神9 小时前
HarmonyOS ArkGraphics 2D 复杂文本排版实操:用 ParagraphBuilder 做资讯阅读卡片
华为·harmonyos
大雷神9 小时前
HarmonyOS ArkGraphics 2D NativeImage 实操:获取 NativeWindow 与 SurfaceId
华为·harmonyos
小玮看世界10 小时前
当“教用户配置系统“成为产品的遮羞布:从鸿蒙拦截栈与小红书联系机制看科技公司的“驯化式创新“
科技·华为·harmonyos
梦想不只是梦与想10 小时前
鸿蒙 应用类型:企业应用
华为·harmonyos·企业应用
无限码力10 小时前
华为非AI方向笔试真题【工厂落点最小加权路程】
算法·华为·华为非ai方向笔试真题·华为笔试真题·华为最新笔试真题·华为笔试题库
大雷神11 小时前
HarmonyOS ArkGraphics 2D 文本绘制实操:用 TextBlob 做动态文字排版
华为·harmonyos
搬砖的kk11 小时前
从 0 到 1:用 KMP + Compose Multiplatform + Ktor 实现鸿蒙「历史上的今天」应用
开源·harmonyos
星辰徐哥11 小时前
鸿蒙PC平台 Gnote 笔记应用适配实战:从 Linux 到 鸿蒙PC 的 Electron 迁移
linux·笔记·electron·harmonyos·gnote
Swift社区11 小时前
鸿蒙 App 如何设计 Memory Center?一文讲透 Agent 的长期记忆架构
华为·架构·harmonyos
binbin_5211 小时前
HarmonyOS 应用功耗优化实战:定位耗电、收口任务与验证回归
android·回归·harmonyos