HarmonyOS Stage 模型架构解析与应用指南
HarmonyOS Stage 模型架构解析与应用指南 自 HarmonyOS 3.1 起,华为正式引入 Stage 模型,并逐步废弃 FA(Feature Ability)模型。在后续版本中,Stage 模型已成为官方唯一推荐的应用架构标准。采用 Stage 模型可更好地支持多设备协同、分布式窗口及后台任务管理等高级特性。 一、Stage 模型 vs FA 模型:架构演进 FA 模型是 Harm…

HarmonyOS Stage 模型架构解析与应用指南 自 HarmonyOS 3.1 起,华为正式引入 Stage 模型,并逐步废弃 FA(Feature Ability)模型。在后续版本中,Stage 模型已成为官方唯一推荐的应用架构标准。采用 Stage 模型可更好地支持多设备协同、分布式窗口及后台任务管理等高级特性。 一、Stage 模型 vs FA 模型:架构演进 FA 模型是 Harm…

自 HarmonyOS 3.1 起,华为正式引入 Stage 模型,并逐步废弃 FA(Feature Ability)模型。在后续版本中,Stage 模型已成为官方唯一推荐的应用架构标准。采用 Stage 模型可更好地支持多设备协同、分布式窗口及后台任务管理等高级特性。
FA 模型是 HarmonyOS 早期采用的架构,能力(Ability)与 UI 强耦合,多窗口与生命周期管理较为复杂。Stage 模型采用**'能力(Ability)+ 窗口(Window)+ 页面(Page)'三层解耦架构**,更符合现代操作系统设计理念。
| 维度 | FA 模型 | Stage 模型 |
|---|---|---|
| 入口 | MainAbility | UIAbility |
| UI 管理 | Ability 直接控制 UI | WindowStage 管理窗口,Page 描述 UI |
| 生命周期 | 分散在 Ability 中 | 由 UIAbility 与 WindowStage 协同管理 |
| 多实例支持 | 实现复杂 | 原生支持(分屏、悬浮窗等) |
| 跨设备协同 | 需手动实现 | 内置 Continuation 能力 |
核心思想:UI 与业务逻辑分离,窗口与页面解耦,能力可复用。
UIAbility 是 Stage 模型中承载 UI 的能力单元,职责比早期的 MainAbility 更加清晰。
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.info('UIAbility onCreate');
}
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
console.error(`Failed to load content: ${JSON.stringify(err)}`);
return;
}
console.info('Content loaded successfully');
});
}
onDestroy() {
console.info('UIAbility onDestroy');
}
}
生命周期说明:
onCreate():Ability 创建时调用,适合初始化全局状态。onWindowStageCreate(windowStage):窗口创建完成,此时可调用 windowStage.loadContent() 加载主页面。onDestroy():Ability 销毁前清理资源。关键点:UI 不再在 Ability 中定义,而是在独立的 Page 文件中描述。
WindowStage 代表一个应用窗口实例,负责加载页面内容、管理窗口属性(大小、透明度、焦点)及处理窗口生命周期事件。
// 在 UIAbility 中获取并配置 WindowStage
onWindowStageCreate(windowStage: window.WindowStage) {
const mainWindow = windowStage.getMainWindowSync();
mainWindow.setWindowBackgroundColor('#FFFFFF');
windowStage.loadContent('pages/Index', (err) => { /* ... */ });
}
典型应用场景:全屏游戏设置、悬浮窗创建、多窗口协同管理。
Context 是访问系统服务、资源与能力的统一入口。在 ArkTS 页面组件中,可通过 getContext(this) 获取。
import common from '@ohos.app.ability.common';
import { getContext } from '@kit.ArkUI';
@Entry
@Component
struct MyPage {
build() {
Column() {
Button("获取上下文信息").onClick(() => {
const context = getContext(this) as common.UIAbilityContext;
const config = context.config;
console.info(`Screen: ${config.screenWidth} x ${config.screenHeight}`);
})
}
}
}
关键 API:
getContext(this):在 @Component 中安全获取上下文(this 必须为组件实例)。context.config:获取设备配置(屏幕宽高、DPI、语言等)。context.getUIAbility():获取当前 UIAbility 实例。context.resourceManager:访问字符串、图片等本地资源。Stage 模型引入了新的配置文件体系,取代了 FA 模型的 config.json。
main_pages.json:页面路由清单路径:src/main/resources/base/profile/main_pages.json
{
"src": [
"pages/Index",
"pages/Detail"
]
}
作用:声明所有可被 loadContent() 加载的页面路径(相对于 src/main/ets)。必须显式注册,否则加载会失败。建议按功能模块组织路径。
module.json5:模块级配置路径:src/main/module.json5
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": ["phone", "tablet"],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/UIAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["action.system.home"]
}
]
}
]
}
}
关键字段:mainElement 指定入口 Ability 类名;pages 引用路由清单;abilities 数组定义模块包含的能力。
build-profile.json5:构建配置路径:项目根目录 /build-profile.json5
{
"app": {
"signingConfigs": [],
"products": [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "6.0.2(22)",
"runtimeOS": "HarmonyOS"
}
]
}
}
作用:指定兼容的 SDK 版本、配置签名与产品变体。需确保 compatibleSdkVersion 与开发环境匹配。
场景:在页面中动态获取屏幕宽高并更新 UI。
import window from '@ohos.window';
import common from '@ohos.app.ability.common';
import { getContext } from '@kit.ArkUI';
@Entry
@Component
struct ScreenInfoPage {
@State screenWidth: number = 0;
@State screenHeight: number = 0;
@State windowMode: string = '未知';
aboutToAppear(): void {
setTimeout(() => this.updateScreenInfo(), 300);
}
updateScreenInfo(): void {
try {
const context = getContext(this) as common.UIAbilityContext;
if (!context) {
console.error('获取 Context 失败');
return;
}
const windowStage = context.windowStage;
if (windowStage) {
const mainWindow = windowStage.getMainWindowSync();
const windowProperties = mainWindow.getWindowProperties();
this.screenWidth = windowProperties.windowRect.width;
this.screenHeight = windowProperties.windowRect.height;
}
if (context.abilityInfo) {
console.info('UIAbility name:', context.abilityInfo.name);
}
} catch (e) {
console.error('更新屏幕信息失败:', JSON.stringify(e));
}
}
build() {
Column() {
Text(`屏幕尺寸:${this.screenWidth} x ${this.screenHeight}`)
.fontSize(18)
Text(`窗口模式:${this.windowMode}`)
.fontSize(16)
.margin({ top: 10 })
Button("刷新信息")
.onClick(() => this.updateScreenInfo())
.margin({ top: 20 })
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
.backgroundColor('#f0f0f0')
}
}
代码解析:
getContext(this) 安全获取上下文。context.windowStage.getMainWindowSync() 同步获取主窗口实例。windowRect 属性获取实时宽高,避免异步回调嵌套。A:可通过 Ability 的 context 属性进行传递,或使用 ApplicationContext(需申请相应权限)。
main_pages.json 能否动态修改?A:不能。所有页面必须在编译时静态注册,这是出于安全与路由性能优化的考虑。
UIAbility 仅负责一类核心功能(如主界面、独立设置页)。UIAbility 中,Page 仅负责 UI 渲染与交互逻辑。Stage 模型通过 Ability、Window、Page 三层解耦,实现了更清晰的生命周期管理与多设备适配能力。作为 HarmonyOS 官方长期维护的架构标准,深入理解其核心机制是开发高质量鸿蒙应用的基础。建议新项目直接采用 Stage 模型,老项目可借助官方迁移工具逐步重构。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online
将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online