《卡片添加至桌面》五、postCardAction指南
HarmonyOS postCardAction 指南摘要本文详细介绍 HarmonyOS 卡片事件机制postCardAction的使用方法涵盖call、router、message三种事件类型的用法与区别通过完整代码示例演示卡片与应用主进程之间的交互方式。效果一、概述postCardAction是 HarmonyOS 应用卡片中用于触发交互事件的全局函数。由于卡片运行在桌面进程中非应用进程无法直接使用普通的导航和事件机制。postCardAction提供了一套专门的事件通道让卡片可以与宿主应用进行通信。1.1 三种事件类型事件类型作用触发方式call调用 UIAbility 中注册的 callee 方法卡片内触发主进程 callee 响应router跳转打开应用页面点击后直接打开应用message发送消息到 FormExtensionAbility卡片内触发onFormEvent响应1.2 函数签名postCardAction(component:Object,// 当前组件实例thisactionInfo:{action:call|router|message,abilityName?:string,// call 事件必填目标 UIAbility 名称params?:Recordstring,string// 传递的参数})二、call 事件调用主进程方法call事件是卡片刷新数据最常用的方式。卡片通过postCardAction发送call事件主应用的UIAbility通过callee.on()注册的回调来接收和处理。2.1 流程图卡片 UI (Widget) │ │ postCardAction({ action: call, abilityName: EntryAbility, params: {...} }) ▼ EntryAbility.callee.on(methodName, callback) │ │ 获取最新数据更新 Preferences ▼ formProvider.updateForm(formId, formData) │ ▼ 卡片 UI 自动刷新2.2 卡片端代码letlocalStoragenewLocalStorage();Entry(localStorage)Componentstruct MyWidgetCard{LocalStorageProp(formId)formId:string;LocalStorageProp(batteryLevel)batteryLevel:number0;build(){Column({space:12}){Text(当前电量${this.batteryLevel}%).fontSize(20).fontWeight(FontWeight.Bold)Image($r(app.media.refresh_icon)).width(24).height(24).onClick((){// 发送 call 事件触发主进程刷新数据postCardAction(this,{action:call,abilityName:EntryAbility,params:{formId:this.formId,method:refreshData}});})}.width(100%).height(100%).padding(16)}}2.3 EntryAbility 端代码import{UIAbility}fromkit.AbilityKit;import{rpc}fromkit.IPCKit;import{formBindingData,formProvider}fromkit.FormKit;import{JSON}fromkit.ArkTS;exportdefaultclassEntryAbilityextendsUIAbility{// 定义 callee 回调处理函数refreshData(data:rpc.MessageSequence){// 1. 解析卡片传来的参数letparams:Recordstring,stringJSON.parse(data.readString())asRecordstring,string;letformIdparams.formId;if(formId){// 2. 获取最新数据例如电量信息letbatteryLevelbatteryInfo.batterySOC;// 3. 构造卡片更新数据letformData{formId:formId,batteryLevel:batteryLevel};// 4. 更新卡片letformMsgformBindingData.createFormBindingData(formData);formProvider.updateForm(formId,formMsg).then((){console.info(卡片刷新成功);}).catch((error:Error){console.error(卡片刷新失败:${JSON.stringify(error)});});}returnnull;};onCreate():void{// 注册 callee 回调try{this.callee.on(refreshData,this.refreshData);}catch(err){console.error(注册 callee 失败:${JSON.stringify(err)});}}onDestroy():void{// 取消 callee 注册try{this.callee.off(refreshData);}catch(err){console.error(取消 callee 失败:${JSON.stringify(err)});}}}2.4 关键要点要点说明abilityName必须与module.json5中定义的 UIAbility 名称一致参数格式params是Recordstring, string类型callee 注册在onCreate中注册onDestroy中取消数据处理通过rpc.MessageSequence读取参数三、router 事件跳转打开应用router事件用于点击卡片后打开应用页面是最简单的卡片交互方式。3.1 卡片端代码Entry(localStorage)Componentstruct MyWidgetCard{LocalStorageProp(formId)formId:string;LocalStorageProp(title)title:string;build(){Column(){Text(this.title).fontSize(16).fontWeight(FontWeight.Bold)Text(点击查看详情).fontSize(12).fontColor(#4FC3F7).margin({top:8}).onClick((){postCardAction(this,{action:router,abilityName:EntryAbility,params:{formId:this.formId,page:DetailPage}});})}.width(100%).height(100%).padding(16)}}3.2 EntryAbility 处理跳转在onWindowStageCreate中根据 Want 参数跳转到不同页面onWindowStageCreate(windowStage:window.WindowStage):void{// 检查是否从卡片 router 跳转而来letpagethis.context.want?.parameters?.pageasstring;lettargetPagepage??pages/Index;windowStage.loadContent(targetPage,(err){if(err.code){console.error(加载页面失败:${JSON.stringify(err)});return;}});}3.3 router 事件特点不需要注册 callee会唤醒应用并将应用带到前台适合查看详情等跳转场景四、message 事件发送消息到 FormExtensionAbilitymessage事件将消息发送到FormExtensionAbility的onFormEvent回调中。4.1 卡片端代码Text(发送消息).onClick((){postCardAction(this,{action:message,params:{key:refresh,formId:this.formId}});})4.2 FormExtensionAbility 端接收onFormEvent(formId:string,message:string):void{console.info(收到卡片消息: formId${formId}, message${message});// 解析消息letmsgObjJSON.parse(message)asRecordstring,string;if(msgObj.keyrefresh){// 执行数据刷新逻辑letformData{formId:formId,updated:true};letformMsgformBindingData.createFormBindingData(formData);formProvider.updateForm(formId,formMsg);}}五、三种事件类型对比维度callroutermessage接收端UIAbility (callee)UIAbility (Want)FormExtensionAbility是否唤醒应用唤醒后台应用打开应用到前台不唤醒应用适用场景刷新卡片数据跳转页面简单消息通知参数传递rpc.MessageSequenceWant parametersJSON 字符串复杂度中等低低六、完整实战示例刷新按钮触发数据更新6.1 卡片组件letlocalStoragenewLocalStorage();Entry(localStorage)Componentstruct RefreshableWidgetCard{LocalStorageProp(formId)formId:string;LocalStorageProp(batteryLevel)batteryLevel:number0;LocalStorageProp(storageUsed)storageUsed:string;LocalStorageProp(isRefreshing)isRefreshing:booleanfalse;build(){Column({space:12}){Row(){Text(设备信息).fontSize(14).fontWeight(FontWeight.Bold)Blank()Image($r(app.media.refresh_icon)).width(20).height(20).onClick((){postCardAction(this,{action:call,abilityName:EntryAbility,params:{formId:this.formId,method:refreshAll}});})}.width(100%)Text(电量${this.batteryLevel}%).fontSize(12)Text(存储${this.storageUsed}).fontSize(12)}.width(100%).height(100%).padding(16).backgroundColor(Color.White).borderRadius(12)}}6.2 EntryAbility 处理refreshAll(data:rpc.MessageSequence){letparamsJSON.parse(data.readString())asRecordstring,string;letformIdparams.formId;if(formId){letformData{formId:formId,batteryLevel:batteryInfo.batterySOC,storageUsed:${usedGB.toFixed(1)}/${totalGB.toFixed(1)}GB};letformMsgformBindingData.createFormBindingData(formData);formProvider.updateForm(formId,formMsg);}returnnull;};七、常见问题与注意事项7.1 postCardAction 不生效确认abilityName与module.json5中的名称完全一致确认 callee 已在onCreate中注册确认卡片是通过Entry(localStorage)声明的7.2 call 事件中参数类型params是Recordstring, string类型所有值都是字符串。如果需要传递数字需要在接收端进行类型转换。7.3 callee 回调中如何返回数据callee回调的返回值通过rpc.MessageSequence返回给卡片端但在实际使用中卡片数据更新通常通过formProvider.updateForm直接推送。八、总结知识点内容函数postCardAction(this, actionInfo)call 事件调用 UIAbility 中 callee 注册的方法router 事件跳转打开应用页面message 事件发送消息到 FormExtensionAbilitycallee 注册this.callee.on(name, callback)callee 取消this.callee.off(name)参数解析rpc.MessageSequence.readString()postCardAction是 HarmonyOS 卡片交互的核心机制掌握call事件可以实现卡片的实时数据刷新是开发动态应用卡片的必备技能。