HarmonyOS鸿蒙Next中启动页面传参
HarmonyOS鸿蒙Next中启动页面传参 我从外部启动APP,在ability里面want接收到了参数,请问我怎么把参数传到启动的页面里面去?比如,我首页根据这些参数显示不同的样式?
可以使用 want
中的 parameters
参数,可以由自行决定传入的键值对。参考文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-app-ability-want-V5#%E5%B1%9E%E6%80%A7
您可以参考一下这个论坛的内容: https://developer.huawei.com/consumer/cn/forum/topic/0204147471482372080?fid=0102683795438680754
另外使用 EventHub
进行数据通信可以参考:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/uiability-data-sync-with-ui-V5
参考以下 demo:
拉起方 TestA:
//Index.ets
Button('To TestB')
.onClick(() => {
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
let want: Want = {
uri: "link://www.testb.com",
parameters:{
name:'张三'
}
};
try {
context.startAbility(want).then(() => {
console.info('start ability success.');
}).catch((err: BusinessError) => {
console.error(`start ability failed. Code is ${err.code}, message is ${err.message}`);
})
} catch (paramError) {
console.error(`Failed to start ability. Code is ${paramError.code}, message is ${paramError.message}`);
}
})
被拉起方 TestB:
//module.json5
{
"skills": [
{
.....
"uris": [
{
"scheme": "link",
"host": "www.testb.com",
}
]
}
]
}
//EntryAbility.ets
let storage: LocalStorage = new LocalStorage();
export default class EntryAbility extends UIAbility {
..
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onNewWant');
let parameters = want.parameters
if (parameters == null || parameters == undefined) {
console.error('获取拉起方A的want失败')
return
}
let name = want.parameters?.name
console.log("Ability onNewWant:" + name)
storage.setOrCreate('name',name)
}
..
}
//Index.ets
onPageShow(): void {
let storageProcess = LocalStorage.getShared()
let name = storageProcess.get("name") as string
console.log("onPageShow: " + name);
}
更多关于HarmonyOS鸿蒙Next中启动页面传参的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,启动页面传参主要通过Intent
对象实现。Intent
是鸿蒙系统中用于在页面之间传递数据和执行操作的核心机制。开发者可以通过Intent
携带参数,并在目标页面中接收这些参数。
具体步骤如下:
-
创建Intent对象:在源页面中,使用
Intent
对象指定目标页面,并通过Intent
的setParam
方法设置参数。let intent = new Intent(); intent.setComponent({ bundleName: 'com.example.myapplication', abilityName: 'TargetAbility' }); intent.setParam('key', 'value'); this.context.startAbility(intent);
-
接收参数:在目标页面的
onCreate
或onNewIntent
方法中,通过Intent
对象获取传递的参数。class TargetAbility extends Ability { onCreate(want) { let param = want.parameters['key']; // 使用参数 } }
通过这种方式,开发者可以在HarmonyOS鸿蒙Next中实现页面间的参数传递。
在HarmonyOS鸿蒙Next中,启动页面时可以通过Intent
对象传递参数。具体步骤如下:
-
创建Intent对象:
Intent intent = new Intent(); intent.setOperation(new Intent.OperationBuilder() .withDeviceId("") .withBundleName("com.example.myapp") .withAbilityName("com.example.myapp.MainAbility") .build());
-
添加参数:
intent.setParam("key", "value");
-
启动页面:
startAbility(intent);
-
在目标页面获取参数:
String value = getIntent().getStringParam("key");
通过Intent
对象,可以灵活地在页面间传递数据,支持多种数据类型。