跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
TypeScript大前端

HarmonyOS Stage 模型详解:从架构演进到实战落地

HarmonyOS 6.0 时代 Stage 模型已成唯一标准。对比 FA 模型缺陷,解析 UIAbility、WindowStage、Context 三大核心概念,详解 module.json5 等配置文件结构,并提供获取屏幕尺寸与窗口信息的 ArkTS 实战代码。适合希望迁移至新架构或深入理解鸿蒙应用生命周期的开发者参考。

板砖工程师发布于 2026/3/22更新于 2026/9/459 浏览
HarmonyOS Stage 模型详解:从架构演进到实战落地

HarmonyOS Stage 模型详解:从架构演进到实战落地

自 HarmonyOS 3.1 起,华为正式引入 Stage 模型,并宣布 FA(Feature Ability)模型逐步废弃。在 HarmonyOS 6.0.0(API 6.0.2) 时代,Stage 模型已成为唯一推荐的应用架构标准。

如果你仍在使用 FA 模型,你的应用将面临无法上架新版应用市场、失去最新 UI 能力支持以及难以适配多设备协同等风险。本文将带你彻底搞懂 Stage 模型,涵盖核心差异、三大概念、项目结构及屏幕尺寸获取实战。

一、Stage 模型 vs FA 模型:架构演进

1. FA 模型(已废弃)

FA 模型是早期架构,灵感来自 Android 的 Activity/Service 模式。

// FA 模型示例(已不推荐)
export default class MainAbility extends Ability {
    onCreate() {
        // 初始化逻辑
    }
}

FA 模型的缺陷在于能力与 UI 强耦合,多窗口管理复杂,且缺乏统一的生命周期管理,难以支持跨设备协同。

2. Stage 模型(现代标准)

Stage 模型采用 '能力 + 窗口 + 页面'三层解耦架构,更符合现代操作系统设计理念。

维度FA 模型Stage 模型
入口MainAbilityUIAbility
UI 管理Ability 直接控制 UIWindowStage 管理窗口,Page 描述 UI
生命周期分散在 Ability 中统一由 UIAbility 和 WindowStage 协同管理
多实例支持困难原生支持(如分屏、悬浮窗)
跨设备协同需手动实现内置 Continuation 能力

💡 核心思想:UI 与业务逻辑分离,窗口与页面解耦,能力可复用。

二、Stage 模型三大核心概念

1. UIAbility:应用的能力入口

UIAbility 是承载 UI 的能力单元,职责比 FA 中的 MainAbility 更清晰。

// src/main/ets/UIAbility.ts
import UIAbility from '@ohos.app.ability.UIAbility';

export default class EntryAbility extends UIAbility {
    onCreate(want, launchParam) {
        console.log('UIAbility created');
    }

    onWindowStageCreate(windowStage) {
        // 关键:在此加载主页面
        windowStage.loadContent('pages/Index', (err, data) => {
            if (err.code) {
                console.error('Failed to load content: ' + JSON.stringify(err));
                return;
            }
            console.log('Content loaded successfully');
        });
    }

    onDestroy() {
        console.log('UIAbility destroyed');
    }
}
  • onCreate():Ability 创建时调用,适合初始化全局状态。
  • onWindowStageCreate(windowStage):窗口创建完成,此时可加载页面。
  • windowStage.loadContent('pages/Index'):指定主页面路径(相对于 src/main/ets)。
  • onDestroy():Ability 销毁前清理资源。

📌 关键点:UI 不再在 Ability 中定义,而是在独立的 Page 文件中描述(如 Index.ets)。

2. WindowStage:窗口管理中枢

WindowStage 代表一个应用窗口实例,负责加载页面内容、管理窗口属性及处理生命周期事件。

// 在 UIAbility 中获取 WindowStage
onWindowStageCreate(windowStage: window.WindowStage) {
    // 获取窗口对象
    const window = windowStage.getMainWindowSync();
    // 设置窗口背景色
    window.setWindowBackgroundColor('#FFFFFF');
    // 加载页面
    windowStage.loadContent('pages/Index', callback);
}

典型应用场景包括全屏游戏(window.setFullScreen(true))、通过 windowManager 创建新 WindowStage 实现悬浮窗,以及多窗口协同。

3. Context:上下文获取桥梁

Context 是访问系统服务、资源、能力的统一入口。在 ArkTS 中,通过 getContext(this) 获取。

// 在 Page 组件中获取 Context
@Entry
@Component
struct MyPage {
    build() {
        Column() {
            Button("获取屏幕信息").onClick(() => {
                const context = getContext(this);
                const config = context.config;
                const ability = context.getUIAbility();
                
                console.log(`Screen: ${config?.screenWidth} x ${config?.screenHeight}`);
            })
        }
    }
}
  • getContext(this):在 @Component 中获取上下文。
  • context.config:获取设备配置(屏幕宽高、DPI、语言等)。
  • context.getUIAbility():获取当前 UIAbility 实例。

⚠️ 注意:getContext(this) 中的 this 必须是 @Component 装饰的 struct 实例,否则会报错。

三、项目结构文件详解(Stage 模型专属)

Stage 模型引入了新的配置文件体系,取代 FA 模型的 config.json。

1. main_pages.json:页面路由清单

路径:src/main/resources/base/profile/main_pages.json

{"src": ["pages/Index", "pages/Detail"]}

作用:声明所有可被 loadContent() 加载的页面路径;路径相对于 src/main/ets;必须显式注册,否则 loadContent 会失败。

💡 最佳实践:主页面放第一个;按功能模块组织路径(如 pages/game/Level1)。

2. 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"]
          }
        ]
      }
    ]
  }
}

📌 重要变化:FA 模型的 config.json 已被 module.json5 + main_pages.json 取代,配置更模块化、可读性更强。

3. build-profile.json5:构建配置

路径:项目根目录 /build-profile.json5

{
  "app": {
    "signingConfigs": [],
    "products": [
      {
        "name": "default",
        "signingConfig": "default",
        "compatibleSdkVersion": "6.0.2(22)",
        "runtimeOnly": false
      }
    ]
  }
}

作用:指定兼容的 SDK 版本(compatibleSdkVersion);配置签名、产品变体;控制是否仅运行时(runtimeOnly)。

✅ 适配提示:此处必须匹配虚拟机 API 版本(如 6.0.2),否则安装失败。

四、实战:获取屏幕尺寸、窗口、能力上下文

场景:在页面中动态获取屏幕宽高并调整 UI

// 导入正确的模块和类型(适配 API 6.0.2)
import window from '@ohos.window';
import common from '@ohos.app.ability.common';

@Entry
@Component
struct ScreenInfoPage {
    @State screenWidth: number = 0;
    @State screenHeight: number = 0;
    @State windowMode: string = 'API 6 不支持获取';

    aboutToAppear(): void {
        // 延迟执行,确保窗口已创建
        setTimeout(() => {
            this.updateScreenInfo();
        }, 300);
    }

    updateScreenInfo(): void {
        try {
            // 1. 获取并转换 Context 类型
            const context = getContext(this) as common.UIAbilityContext;
            if (!context) {
                console.error('获取 Context 失败');
                return;
            }

            // 2. 通过 windowStage 获取主窗口尺寸(API 6 兼容方式)
            const windowStage = context.windowStage;
            if (windowStage) {
                const mainWindow = windowStage.getMainWindowSync();
                const windowProperties = mainWindow.getWindowProperties();
                this.screenWidth = windowProperties.windowRect.width;
                this.screenHeight = windowProperties.windowRect.height;
            }

            // 3. 打印 Ability 信息
            if (context.abilityInfo) {
                console.log('UIAbility name:', context.abilityInfo.name);
            }

            // 4. 窗口模式获取在 API 6 中不可用,直接设置提示
            this.windowMode = 'API 6 不支持获取';
        } catch (e) {
            console.error('更新屏幕信息失败:', JSON.stringify(e));
        }
    }

    build() {
        Column() {
            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):在 @Component 中安全获取上下文。
  • context.config:直接读取屏幕宽高(单位:px),无需异步。
  • currentWindowStage.getMainWindowSync():同步获取主窗口(Stage 模型特有)。
  • getWindowMode():判断当前窗口模式(全屏/悬浮等)。

✅ 优势:所有操作均为同步调用,无回调地狱,代码简洁可靠。

五、常见问题与最佳实践

❓ Q1:如何在非 UIAbility 中获取 Context?

A:通过 Ability 的 context 属性传递,或使用 ApplicationContext(需权限)。

❓ Q2:main_pages.json 能否动态修改?

A:不能。所有页面必须在编译时注册,这是出于安全与性能考虑。

✅ 最佳实践:

  • Ability 职责单一:一个 UIAbility 只负责一类功能(如主界面、设置页);
  • 避免在 Page 中持有 Ability 引用:通过事件通信,而非直接调用;
  • 窗口操作放 Ability 中:Page 只负责 UI 描述,窗口管理归 UIAbility。

六、总结:Stage 模型的核心价值

维度价值
架构清晰Ability(能力) + Window(窗口) + Page(页面)三层解耦
生命周期可控统一入口,便于资源管理与内存优化
多设备友好原生支持手机、平板、车机、手表的窗口适配
未来-proof华为官方唯一维护的模型,持续获得新特性

新项目建议直接使用 Stage 模型;老 FA 项目应尽快迁移;深入理解 UIAbility 与 WindowStage 的协作机制是关键。

目录

  1. HarmonyOS Stage 模型详解:从架构演进到实战落地
  2. 一、Stage 模型 vs FA 模型:架构演进
  3. 1. FA 模型(已废弃)
  4. 2. Stage 模型(现代标准)
  5. 二、Stage 模型三大核心概念
  6. 1. UIAbility:应用的能力入口
  7. 2. WindowStage:窗口管理中枢
  8. 3. Context:上下文获取桥梁
  9. 三、项目结构文件详解(Stage 模型专属)
  10. 1. main_pages.json:页面路由清单
  11. 2. module.json5:模块级配置(核心!)
  12. 3. build-profile.json5:构建配置
  13. 四、实战:获取屏幕尺寸、窗口、能力上下文
  14. 场景:在页面中动态获取屏幕宽高并调整 UI
  15. 五、常见问题与最佳实践
  16. ❓ Q1:如何在非 UIAbility 中获取 Context?
  17. ❓ Q2:main_pages.json 能否动态修改?
  18. ✅ 最佳实践:
  19. 六、总结:Stage 模型的核心价值

更多推荐文章

查看全部
  • 基于 Python 的商品销售数据分析与可视化实战
  • Python AI 实战:从线性回归到 MNIST 图像分类
  • Python 核心语法速查:数据类型与基础操作
  • MaaS 平台与阿里 QWQ 技术:AI 调参实战指南
  • Python 为何成为 AI 开发的首选语言?
  • 浏览器 F5 刷新机制深度解析
  • PHP 使用 Pdo_kdb 驱动连接 Kingbase 数据库实战指南
  • ComfyUI v0.11.1 发布:新增开发者节点、API 强化与 Python 3.14 兼容
  • 从推荐算法转行大模型推理工程:行业趋势与技术路径
  • 网络安全行业主流证书选择指南
  • Git 安装状态检查方法汇总
  • Z-Image-Turbo WebUI 本地部署与使用指南
  • 豆包 Seedream 4.0 多图融合能力测评与实战解析
  • Lit 与 Alpine.js:轻量级前端开发的两种路径
  • 2026 年高薪就业赛道:AI 大数据、大模型、AIGC 与云计算
  • FPGA 高速通信:Aurora 64B/66B IP 核配置与回环实现指南
  • Easylogging++ C++ 日志库使用指南
  • 云服务器 MySQL 8.0 安装与远程连接配置
  • Python 内置函数详解:30 个核心函数语法与案例
  • AIGC 技术全景:原理、应用与未来挑战

相关免费在线工具

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online

  • JSON 压缩

    通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online

  • JSON美化和格式化

    将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online