【背景知识】
多HAP开发是指在HarmonyOS中使用多个应用包(一个entry包和多个feature包)来实现复杂应用的开发方式。这种开发模式允许将复杂应用拆分成多个模块,每个模块可以独立开发、测试和更新,提高了开发效率和维护性。页面路由中的命名路由方法和UIAbility中的startAbility方法提供了跨HAP包的路由跳转功能。
【解决方案】
方案一:使用命名路由法
- 导入router模块:
import { router } from '@kit.ArkUI';
- 在想要跳转到的HAP模块的页面里,给@Entry修饰的自定义组件EntryOptions命名,代码示例如下:
[@Entry](/user/Entry)({ routeName : 'myPage' })
@Component
export struct MyHapComponent {
// HAP模块中自定义组件内容
}
- 配置成功后需要在跳转的页面中引入命名路由的页面,代码示例如下:
import { BusinessError } from '@kit.BasicServicesKit';
import '@ohos/library/src/main/ets/pages/Index'; // 引入共享包中的命名路由页面
[@Entry](/user/Entry)
@Component
struct Index {
build() {
RelativeContainer() {
Button('跳转HAP命名路由法')
.fontSize(25)
.width(350)
.height(50)
.margin({ top: 400 })
.alignRules({
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
// 点击跳转到被命名为'myPage'的HAP模块的页面
try {
this.getUIContext().getRouter().pushNamedRoute({
name: 'myPage'
})
} catch (err) {
let message = (err as BusinessError).message
let code = (err as BusinessError).code
console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
}
})
}
.height('100%')
.width('100%')
}
}
注意:
- 使用命名路由方式跳转时,需要在当前应用包的oh-package.json5文件中配置依赖。代码示例如下:
"dependencies": {
"@ohos/library": "file:../library",
// ...
}
- 在代码编辑完成后,需要将所有更改过的模块包都重新构建再调试,否则会报错。
方案二:使用startAbility方法
startAbility方法只需配置使用页面路由的页面,示例代码如下:
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
const BUNDLE_NAME: string = 'com.example.routeDemo' // 在应用app.json5文件中"bundleName"节点获得
const ABILITY_NAME: string = "hapPageAbility" // 在HAP包的对应Ability文件中获得
[@Entry](/user/Entry)
@Component
struct Index {
@State message: string = 'Hello World';
private context?: common.UIAbilityContext // 创建context实例
aboutToAppear(): void {
this.context = getContext(this) as common.UIAbilityContext // 获取当前页面关联的UIAbilityContext
}
jumpHap() {
if (this.context) {
// 启动Ability,拉起HAP模块的UIAbility实例
this.context.startAbility({
bundleName: BUNDLE_NAME,
abilityName: ABILITY_NAME
}).then(() => {
console.info('start audio ability success')
}).catch((error: BusinessError) => {
console.error('start audio ability failed, error: ' + JSON.stringify(error))
})
}
}
build() {
RelativeContainer() {
Button('startAbility跳转HAP')
.fontSize(25)
.width(350)
.height(50)
.margin({ top: 400 })
.alignRules({
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.jumpHap() // 点击跳转
})
}
}
}
【常见FAQ】
Q:未来是否有支持使用Navigation操作直接跨HAP模块跳转页面的计划?
A:未来也不会支持使用Navigation操作直接跨HAP模块跳转页面。