HarmonyOS之启动应用内的UIAbility组件
📌 一、什么是 UIAbility?
UIAbility 是一种前台组件,具有独立的生命周期,支持界面展示与交互,通常用于实现应用的页面跳转、功能模块隔离等。
✅ 二、启动 UIAbility 的方式(应用内)
方式:使用 显式 Want 启动(推荐方式)
显式 Want 是指通过明确的 bundleName
与 abilityName
启动目标 UIAbility,适用于应用内跳转、页面导航等场景。
🧱 三、关键步骤与示例
🔹 1. 构建 Want 对象并调用 startAbility
import { common } from '@kit.AbilityKit';@Entry
@Component
struct StartAbilityExample {private context = this.getUIContext().getHostContext() as common.UIAbilityContext;startTargetAbility() {const wantInfo = {bundleName: 'com.example.myapp', // 当前应用的包名abilityName: 'TargetAbility', // 目标 UIAbility 名称parameters: { // 可选参数传递userId: '12345',fromPage: 'MainPage'}};this.context.startAbility(wantInfo).then(() => console.log('UIAbility 启动成功')).catch((err) => console.error('UIAbility 启动失败:', err));}build() {Column() {Button('启动 UIAbility').onClick(() => this.startTargetAbility())}}
}
🔹 2. 目标 UIAbility 的配置(module.json5)
{"abilities": [{"name": "TargetAbility","exported": true, // 必须为 true,允许被外部调用"launchType": "standard" // 启动模式(见下方)}]
}
⚠️
exported: true
是必须的,即使在同一个应用内启动。
🧭 四、启动模式(launchType)
模式 | 含义 | 场景示例 |
---|---|---|
standard | 每次启动创建新实例(默认) | 一般页面跳转 |
singleton | 同一实例复用,重复启动不新建 | 首页、设置页等 |
specified | 根据 key 区分实例,支持多个独立实例 | 聊天页面、详情页等需并行存在的界面 |
使用 specified
例子:
{"name": "ChatAbility","exported": true,"launchType": "specified"
}
搭配
onAcceptWant(want: Want)
回调判断是否新建实例。
🔁 五、带结果返回的 UIAbility 启动方式
🔸 调用方使用 startAbilityForResult
this.context.startAbilityForResult(want).then((result) => {if (result?.resultCode === 200) {const data = result.want?.parameters?.resultData;console.log('收到返回值:', data);}
});
🔸 被调用方使用 terminateSelfWithResult
this.context.terminateSelfWithResult({resultCode: 200,want: {parameters: {resultData: '处理结果'}}
});
📄 六、页面跳转控制(传递页面路径)
启动方传页面参数:
const want = {bundleName: 'com.example.myapp',abilityName: 'TargetAbility',parameters: {targetPage: 'pages/ProfilePage'}
};
目标 UIAbility 加载指定页面:
onCreate(want: Want) {const targetPage = want.parameters?.targetPage || 'pages/Index';windowStage.loadContent(targetPage);
}onNewWant(want: Want) {const targetPage = want.parameters?.targetPage;if (targetPage) {this.updatePage(targetPage); // 你需要定义 updatePage 方法}
}
🚧 七、注意事项与常见错误
项目 | 说明 |
---|---|
✅ 包名与组件名准确 | bundleName 和 abilityName 必须精确匹配 module.json5 中定义 |
✅ 设置 exported: true | 否则 UIAbility 无法被启动 |
✅ 依赖声明 | 跨模块调用需在 module.json5 中声明 module 依赖 |
⚠️ 参数格式 | Want.parameters 只支持基础类型或可序列化对象 |
⚠️ 启动过程异步 | 不可在 UI 中阻塞等待返回结果 |
⚠️ 页面路径匹配 | targetPage 参数必须是有效页面路径(例如 pages/xxx ) |
📌 八、总结:常用场景对应方法
需求场景 | 使用方法 |
---|---|
普通页面跳转 | startAbility() |
跳转并返回数据 | startAbilityForResult() + terminateSelfWithResult() |
指定页面跳转 | Want.parameters.targetPage + windowStage.loadContent() |
控制实例复用 | 配置 launchType + onAcceptWant() |