HarmonyOS之AbilityStage、UIAbility、WindowStage - 详解

一、核心组件功能与作用

1. AbilityStage:模块级容器
  • 功能:管理 HAP 模块的生命周期和资源分配,全局响应系统事件(如配置变更、内存压力)。
  • 核心作用
    • 模块初始化:在 HAP 首次加载时通过 onCreate() 预加载资源(如多语言文件、数据库连接池)。
    • 事件响应
      • onConfigurationUpdated():响应系统语言/深色模式切换,更新模块级配置。
      • onMemoryLevel():根据内存压力等级(如 COMPLETE)释放非关键资源(如清空缓存)。
    • 启动模式拦截:通过 onAcceptWant() 管理 specified 模式的 Ability 启动,实现自定义实例复用逻辑。

代码示例(资源预加载与内存管理):

import { AbilityStage, AbilityConstant
} from '@kit.AbilityKit';
export default class MyAbilityStage
extends AbilityStage {
private cacheMap: Map<
string, any>
= new Map();
onCreate(): void {
this.preloadCommonResources();
// 预加载多语言资源
}
onMemoryLevel(level: AbilityConstant.MemoryLevel): void {
if (level === AbilityConstant.MemoryLevel.COMPLETE) {
this.cacheMap.clear();
// 内存不足时释放缓存
}
}
}

2. UIAbility:交互逻辑核心
  • 功能:管理界面生命周期、处理用户交互、实现跨页面导航。
  • 核心作用
    • 生命周期管理
      • onCreate():初始化页面数据。
      • onForeground():申请资源(如重新连接网络)。
      • onBackground():保存状态并释放资源(如暂停动画)。
    • 多实例模式
      • singleton(单例):全局唯一实例(如设置页)。
      • multiton(多实例):每次启动新实例(如多个商品详情页)。
      • specified(指定实例):通过 Key 复用特定实例(如聊天窗口)。
    • 数据同步:通过 EventHubAppStorage 实现跨组件通信。

代码示例(页面跳转与参数传递):

import { UIAbility
} from '@kit.AbilityKit';
import { router
} from '@ohos.router';
export default class ProductAbility
extends UIAbility {
onStart() {
// 跳转到详情页并传递商品ID
router.pushUrl({
url: 'pages/Detail',
params: { productId: '123'
}
});
}
}

3. WindowStage:窗口渲染中枢
  • 功能:管理窗口生命周期、加载 UI 内容、处理窗口级事件(如显示/隐藏)。
  • 核心作用
    • 窗口绑定
      • onWindowStageCreate():加载 UI 组件(如 loadContent('pages/Index'))。
      • onWindowStageDestroy():释放窗口相关资源(如关闭解码器)。
    • 系统交互:控制全屏、分屏、窗口尺寸调整等行为。

代码示例(全屏控制):

import { UIAbility, window
} from '@kit.AbilityKit';
export default class VideoAbility
extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Player', (err) =>
{
if (err) return;
windowStage.getMainWindow().then(win =>
{
win.setFullScreen(true);
// 播放页强制全屏
});
});
}
}

二、三组件协作流程

1. 启动模块时序
阶段AbilityStageUIAbilityWindowStage
初始化模块onCreate() 预加载资源--
首次打开界面-onCreate()onStart()onWindowStageCreate()
切到前台-onForeground()窗口事件 ShownActive
切到后台响应 onMemoryLevel()onBackground()窗口事件 Hidden
销毁模块onDestroy() 回收资源onDestroy()onWindowStageDestroy()
2. 事件协作案例:系统语言切换
  1. AbilityStageonConfigurationUpdated() 捕获变更,更新模块级语言配置。
  2. UIAbility 接收事件,通过 EventHub 通知所有页面重绘:
    // UIAbility中订阅配置变更
    this.context.eventHub.on('langChange', () =>
    {
    router.getActivePage()?.refreshText();
    });
  3. WindowStage 确保新语言下的布局适配(如阿拉伯语右对齐)。

三、综合案例:智能家居控制应用

场景描述
  • AbilityStage:预加载设备列表和房间配置。
  • UIAbility
    • 主页面显示房间列表(singleton 模式)。
    • 设备控制页(multiton 模式,每个设备独立实例)。
  • WindowStage:控制页全屏显示,退出时释放传感器资源。
代码实现

1. AbilityStage 预加载设备数据

// MyAbilityStage.ets
onCreate(): void {
const deviceList = preloadDeviceConfig();
// 从云端加载设备配置
AppStorage.setOrCreate('deviceList', deviceList);
}

2. UIAbility 管理设备控制页

// DeviceAbility.ets
onStart() {
const deviceId = router.getParams()?.['deviceId'];
const device = AppStorage.get('deviceList').find(d => d.id === deviceId);
this.initDeviceControl(device);
// 初始化设备控制逻辑
}

3. WindowStage 全屏与资源释放

// DeviceAbility.ets
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/DeviceControl', () =>
{
windowStage.getMainWindow().setFullScreen(true);
});
}
onWindowStageDestroy() {
releaseSensorResources();
// 释放温度/湿度传感器连接
}
配置变更响应流程

当用户切换深色模式时:

  1. AbilityStageonConfigurationUpdated() → 更新模块主题色。
  2. UIAbility → 通过 EventHub 通知所有页面切换主题。
  3. WindowStage → 调整窗口亮度以适应深色模式。

总结

  • AbilityStage:模块级沙盒,管理全局资源与事件
  • UIAbility:交互中枢,处理页面生命周期与导航
  • WindowStage:渲染引擎,打通系统窗口与UI内容
    三者通过分层协作(模块→交互→渲染),实现鸿蒙应用的高效运行。开发者需在 module.json5 中正确配置入口(如 srcEntry),并在代码中合理分配职责。
posted @ 2025-08-09 14:58  wzzkaifa  阅读(62)  评论(0)    收藏  举报