在鸿蒙 Next 开发中,Stage 模型是应用开发的核心架构之一,它为开发者提供了一种高效、灵活的方式来构建分布式应用。本文将详细介绍鸿蒙 Stage 模型的基本概念、应用配置文件的使用、UIAbility 组件的介绍以及如何通过 Stage 模型开发复杂应用。
Stage 模型是鸿蒙 HarmonyOS API 9 开始新增的应用模型,是目前主推且会长期演进的模型。在 Stage 模型中,应用组件(如 Ability)和窗口(Window)的管理通过 AbilityStage
和 WindowStage
类来实现,因此得名 Stage 模型。
与 FA(Feature Ability)模型相比,Stage 模型的主要区别在于:
应用需要在工程的 AppScope
目录下的 app.json5
文件中配置 bundleName
标签,用于标识应用的唯一性。推荐采用反域名形式命名(如 com.example.demo
)。
图标和标签通常一起配置,分别对应 app.json5
和 module.json5
文件中的 icon
和 label
标签。
Module 支持的设备类型需要在 module.json5
文件中配置 deviceTypes
标签。
Module 访问系统或其他应用受保护部分所需的权限信息需要在 module.json5
文件中配置 requestPermissions
标签。
UIAbility 是一种包含 UI 的应用组件,主要用于与用户交互。一个应用可以有一个或多个 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 的 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 类拥有自身的上下文信息,该信息为 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 模型进行应用开发。如果有任何问题或需要进一步讨论,欢迎随时交流!