鸿蒙Next中如何使用url scheme
在鸿蒙Next系统中,如何通过url scheme实现应用间的跳转?具体需要哪些配置步骤?能否提供示例代码说明调用方法?
2 回复
在鸿蒙Next中,使用URL Scheme就像给应用发“暗号”:
- 在
module.json5里配置abilities的schemes字段,比如["myapp"]。 - 调用
openUrl()方法,传入myapp://page/home就能跳转。 注意:别把Scheme写成“蜜雪冰城甜蜜蜜”,系统会懵的!
更多关于鸿蒙Next中如何使用url scheme的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next(HarmonyOS NEXT)中,使用URL Scheme可以通过Want对象实现应用间的跳转或调用特定功能。以下是基本使用方法:
1. 配置URL Scheme
在module.json5文件中,为Ability声明URL Scheme:
{
"module": {
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["action.system.home"],
"uris": [
{
"scheme": "myapp", // 自定义协议名
"host": "example",
"port": "8080", // 可选
"path": "detail" // 可选路径
}
]
}
]
}
]
}
}
2. 通过URL Scheme启动应用
在代码中使用Want对象触发:
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
let wantInfo: common.Want = {
uri: 'myapp://example/detail?id=123' // 匹配配置的scheme+host+path
};
context.startAbility(wantInfo).then(() => {
hilog.info(0x0000, 'testTag', 'Succeeded in starting ability.');
}).catch((error) => {
hilog.error(0x0000, 'testTag', 'Failed to start ability. Error: %{public}s', error.message);
});
3. 解析传入的URL参数
在目标Ability的onCreate或onNewWant中获取参数:
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let uri = want.uri;
if (uri) {
// 解析URL中的参数(例如:id=123)
let params = new URL(uri).searchParams;
let id = params.get('id');
hilog.info(0x0000, 'testTag', 'Received ID: %{public}s', id);
}
}
}
注意事项:
- 唯一性:URL Scheme应在设备上唯一,避免冲突。
- 权限:确保调用方和应用具备相应权限。
- 错误处理:捕获启动失败情况(如未安装应用)。
通过以上步骤,即可在鸿蒙Next中实现URL Scheme的配置与调用。

