一、变更原因与迁移必要性
1.设计模式优化
(1)旧版 getContext() 缺乏动态响应能力(如折叠屏状态变化)。
(2)UIContext 支持事件监听机制(如安全区域变化 avoidAreaChange 事件),实现实时更新。
2.API 统一性
(1)所有 UI 相关操作收敛到 UIContext,避免全局对象污染,契合 Stage 模型的组件化思想15。
3.未来兼容性
(1)官方明确警告:废弃接口可能在后续版本被移除,继续使用将导致应用崩溃。
二、替代方案的核心:UIContext 体系
在 API 18 中,鸿蒙引入了 UIContext 作为上下文管理的统一入口,替代了原先分散的全局方法。具体替代方式如下:
1. 组件内获取上下文
在 UI 组件(如 @Component 修饰的 ArkTS 组件)中,直接通过 this.getUIContext() 获取:
// 获取 UIContext 实例
const uiContext = this.getUIContext();
// 获取 HostContext(等价于旧版 getContext())
const hostContext = uiContext.getHostContext();
此方式适用于页面布局、弹窗调用、路由跳转等场景。
2. Ability 中获取上下文
在 EntryAbility 的 onWindowStageCreate 阶段,需通过窗口实例获取 UIContext:
windowStage.getMainWindow().then((win) => {
const uiContext = win.getUIContext(); // 获取 UIContext
const hostContext = uiContext.getHostContext(); // 获取上下文
});
注意:禁止使用 getMainWindowSync(),否则会报错 This window state is abnormal。
3. 工具类或静态方法中获取
非组件环境中(如工具类),需通过 AppStorageV2 连接 UIContext:
const context = AppStorageV2.connect(UIContext, 'uiContext', () => new UIContext())
?.getHostContext();
三、总结
1.核心替代方案
使用 this.getUIContext().getHostContext() 或窗口级 win.getUIContext() 替代 getContext()。
2.迁移价值
新 API 在实时性(如动态布局)、安全性(细粒度权限)、多设备支持(折叠屏/分屏)等方面显著优化。
3.紧迫性
华为已逐步移除废弃接口,若不迁移,应用在鸿蒙 NEXT 新机型上可能无法运行。