鸿蒙的 Stage 模型
在鸿蒙 Next 开发中,Stage 模型是应用开发的核心架构之一,它为开发者提供了一种高效、灵活的方式来构建分布式应用。本文将详细介绍鸿蒙 Stage 模型的基本概念、应用配置文件的使用、UIAbility 组件的介绍以及如何通过 Stage 模型开发复杂应用。
一、Stage 模型的基本概念
(一)什么是 Stage 模型?
Stage 模型是鸿蒙 HarmonyOS API 9 开始新增的应用模型,是目前主推且会长期演进的模型。在 Stage 模型中,应用组件(如 Ability)和窗口(Window)的管理通过 AbilityStage
和 WindowStage
类来实现,因此得名 Stage 模型。
(二)Stage 模型与 FA 模型的区别
与 FA(Feature Ability)模型相比,Stage 模型的主要区别在于:
- 资源共享:Stage 模型中,多个应用组件共享同一个 ArkTS 引擎实例,而 FA 模型中,每个应用组件独享一个 ArkTS 引擎实例。
- 内存占用:由于资源共享,Stage 模型在运行复杂应用时可以减少内存占用。
(三)Stage 模型的优势
- 组件间共享:应用组件之间可以方便地共享对象和状态。
- 分布式场景支持:更适合开发分布式场景下的复杂应用。
二、Stage 模型的应用配置文件
(一)应用包名配置
应用需要在工程的 AppScope
目录下的 app.json5
文件中配置 bundleName
标签,用于标识应用的唯一性。推荐采用反域名形式命名(如 com.example.demo
)。
(二)图标和标签配置
图标和标签通常一起配置,分别对应 app.json5
和 module.json5
文件中的 icon
和 label
标签。
(三)Module 支持的设备类型配置
Module 支持的设备类型需要在 module.json5
文件中配置 deviceTypes
标签。
(四)Module 权限配置
Module 访问系统或其他应用受保护部分所需的权限信息需要在 module.json5
文件中配置 requestPermissions
标签。
三、Stage 模型的 UIAbility 组件
(一)UIAbility 组件简介
UIAbility 是一种包含 UI 的应用组件,主要用于与用户交互。一个应用可以有一个或多个 UIAbility,例如,在支付应用中,可以将入口功能和收付款功能分别配置为独立的 UIAbility。
(二)UIAbility 的配置
为使应用能够正常使用 UIAbility,需要在 module.json5
文件的 abilities
标签中声明 UIAbility 的名称、入口、标签等相关信息。
{"module": {"abilities": [{"name": "EntryAbility","srcEntry": "./ets/entryability/EntryAbility.ets","description": "$string:EntryAbility_desc","icon": "$media:icon","label": "$string:EntryAbility_label","startWindowIcon": "$media:icon","startWindowBackground": "$color:start_window_background"}]}
}
(三)指定 UIAbility 的启动页面
在 UIAbility 的 onWindowStageCreate
生命周期回调中,通过 WindowStage
对象的 loadContent
方法设置启动页面。
onWindowStageCreate(windowStage: window.WindowStage): void {windowStage.loadContent('pages/Index', (err) => {if (err.code) {hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');return;}hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');});
}
(四)获取 UIAbility 的上下文信息
UIAbility 类拥有自身的上下文信息,该信息为 UIAbilityContext
类的实例。通过 UIAbilityContext
可以获取 UIAbility 的相关配置信息。
export default class EntryAbility extends UIAbility {onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {let context = this.context;hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');}
}
四、总结
Stage 模型是鸿蒙 HarmonyOS 推荐的应用开发模型,它通过资源共享和高效的组件管理,为开发者提供了一种灵活且高效的方式来构建分布式应用。通过合理配置应用配置文件和使用 UIAbility 组件,开发者可以轻松实现复杂应用的开发。
希望本文能帮助你更好地理解和使用鸿蒙 Stage 模型进行应用开发。如果有任何问题或需要进一步讨论,欢迎随时交流!