鸿蒙HarmonyOS实战-Stage模型(开发卡片事件)
一、开发卡片事件
HarmonyOS元服务卡片页面(Metaservice Card Page)是指在HarmonyOS系统中,用于展示元服务的页面界面。元服务是指一组提供特定功能或服务的组件,例如天气服务、音乐播放服务等。元服务卡片页面可以显示元服务的相关信息和操作选项,用户可以通过点击卡片页面上的按钮或交互元素来使用相关的元服务功能。元服务卡片页面提供了一种快速访问和使用元服务的方式,方便用户进行各种操作和任务。
1.卡片事件能力说明
postCardAction()接口是ArkTS卡片中用于实现卡片内部和提供方应用间交互的方法。目前这个接口支持三种类型的事件:router、message和call,并且仅在卡片中可以调用。
router类型的事件可以用来执行页面跳转或路由切换的操作。通过指定目标路由和传递参数,可以实现页面之间的跳转或路由切换。
message类型的事件用于发送消息或通知给提供方应用。可以通过指定目标应用和消息内容,向提供方应用发送消息或通知。
call类型的事件用于调用提供方应用的函数或方法。可以通过指定目标应用、要调用的函数或方法名以及传递的参数,调用提供方应用中的函数或方法。
postCardAction()接口仅在卡片内部可以调用,无法在提供方应用中直接调用。这个接口提供了卡片和提供方应用之间进行交互的方式,可以实现卡片的功能扩展和与提供方应用的数据交互。

2.使用router事件跳转到指定UIAbility
1、元服务界面
@Entry
@Component
struct WidgetCard {
build() {
Column() {
Button('功能A')
.margin('20%')
.onClick(() => {
console.info('Jump to EntryAbility funA');
postCardAction(this, {
'action': 'router',
'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
'params': {
'targetPage': 'funA' // 在EntryAbility中处理这个信息
}
});
})
Button('功能B')
.margin('20%')
.onClick(() => {
console.info('Jump to EntryAbility funB');
postCardAction(this, {
'action': 'router',
'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
'params': {
'targetPage': 'funB' // 在EntryAbility中处理这个信息
}
});
})
}
.width('100%')
.height('100%')
}
}

2、UIAbility接收参数
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
let selectPage = "";
let currentWindowStage = null;
export default class CameraAbility extends UIAbility {
// 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
// 获取router事件中传递的targetPage参数
console.info("onCreate want:" + JSON.stringify(want));
if (want.parameters.params !== undefined) {
let params = JSON.parse(want.parameters.params);
console.info("onCreate router targetPage:" + params.targetPage);
selectPage = params.targetPage;
}
}
// 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
onNewWant(want, launchParam) {
console.info("onNewWant want:" + JSON.stringify(want));
if (want.parameters.params !== undefined) {
let params = JSON.parse(want.parameters.params);
console.info("onNewWant router targetPage:" + params.targetPage);
selectPage = params.targetPage;
}
if (currentWindowStage != null) {
this.onWindowStageCreate(currentWindowStage);
}
}
onWindowStageCreate(windowStage: window.WindowStage) {
let targetPage;
// 根据传递的targetPage不同,选择拉起不同的页面
switch (selectPage) {
case 'funA':
targetPage = 'pages/FunA';
break;
case 'funB':
targetPage = 'pages/FunB';
break;
default:
targetPage = 'pages/Index';
}
if (currentWindowStage === null) {
currentWindowStage = windowStage;
}
windowStage.loadContent(targetPage, (err, data) => {
if (err && err.code) {
console.info('Failed to load the content. Cause: %{public}s', JSON.stringify(err));
return;
}
});
}
};

3.使用call事件拉起指定UIAbility到后台
1、元服务界面
@Entry
@Component
struct WidgetCard {
build() {
Column() {
Button('功能A')
.margin('20%')
.onClick(() => {
console.info('call EntryAbility funA');
postCardAction(this, {
'action': 'call',
'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
'params': {
'method': 'funA' // 在EntryAbility中调用的方法名
}
});
})
Button('功能B')
.margin('20%')
.onClick(() => {
console.info('call EntryAbility funB');
postCardAction(this, {
'action': 'call',
'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
'params': {
'method': 'funB', // 在EntryAbility中调用的方法名
'num': 1 // 需要传递的其他参数
}
});
})
}
.width('100%')
.height('100%')
}
}
2、UIAbility接收参数
import UIAbility from '@ohos.app.ability.UIAbility';
function FunACall(data) {
// 获取call事件中传递的所有参数
console.log('FunACall param:' + JSON.stringify(data.readString()));
return null;
}
function FunBCall(data) {
console.log('FunACall param:' + JSON.stringify(data.readString()));
return null;
}
export default class CameraAbility extends UIAbility {
// 如果UIAbility第一次启动,在收到call事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
try {
// 监听call事件所需的方法
this.callee.on('funA', FunACall);
this.callee.on('funB', FunBCall);
} catch (error) {
console.log('register failed with error. Cause: ' + JSON.stringify(error));
}
}
// 进程退出时,解除监听
onDestroy() {
try {
this.callee.off('funA');
this.callee.off('funB');
} catch (error) {
console.log('register failed with error. Cause: ' + JSON.stringify(error));
}
}
};
不截图同上
4.通过message事件刷新卡片内容
1、卡片页面
let storage = new LocalStorage();
@Entry(storage)
@Component
struct WidgetCard {
@LocalStorageProp('title') title: string = 'init';
@LocalStorageProp('detail') detail: string = 'init';
build() {
Column() {
Button('刷新')
.onClick(() => {
postCardAction(this, {
'action': 'message',
'params': {
'msgTest': 'messageEvent'
}
});
})
Text(`${this.title}`)
Text(`${this.detail}`)
}
.width('100%')
.height('100%')
}
}
2、卡片FormExtensionAbility
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';
export default class EntryFormAbility extends FormExtensionAbility {
onFormEvent(formId, message) {
// Called when a specified message event defined by the form provider is triggered.
console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);
let formData = {
'title': 'Title Update Success.', // 和卡片布局中对应
'detail': 'Detail Update Success.', // 和卡片布局中对应
};
let formInfo = formBindingData.createFormBindingData(formData)
formProvider.updateForm(formId, formInfo).then((data) => {
console.info('FormAbility updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
})
}
}

5.通过router或call事件刷新卡片内容
5.1 router
1、卡片
let storage = new LocalStorage();
@Entry(storage)
@Component
struct WidgetCard {
@LocalStorageProp('detail') detail: string = 'init';
build() {
Column() {
Button('跳转')
.margin('20%')
.onClick(() => {
console.info('postCardAction to EntryAbility');
postCardAction(this, {
'action': 'router',
'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
'params': {
'detail': 'RouterFromCard'
}
});
})
Text(`${this.detail}`).margin('20%')
}
.width('100%')
.height('100%')
}
}
2、UIAbility
import UIAbility from '@ohos.app.ability.UIAbility';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import formInfo from '@ohos.app.form.formInfo';
export default class EntryAbility extends UIAbility {
// 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
console.info('Want:' + JSON.stringify(want));
if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
let message = JSON.parse(want.parameters.params).detail;
console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
let formData = {
"detail": message + ': onCreate UIAbility.', // 和卡片布局中对应
};
let formMsg = formBindingData.createFormBindingData(formData)
formProvider.updateForm(curFormId, formMsg).then((data) => {
console.info('updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('updateForm failed:' + JSON.stringify(error));
})
}
}
// 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
onNewWant(want, launchParam) {
console.info('onNewWant Want:' + JSON.stringify(want));
if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
let message = JSON.parse(want.parameters.params).detail;
console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
let formData = {
"detail": message + ': onNewWant UIAbility.', // 和卡片布局中对应
};
let formMsg = formBindingData.createFormBindingData(formData)
formProvider.updateForm(curFormId, formMsg).then((data) => {
console.info('updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('updateForm failed:' + JSON.stringify(error));
})
}
}
...
}
5.2 call
1、在使用postCardAction接口的call事件时,需要在FormExtensionAbility中的onAddForm生命周期回调中更新formId。
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class EntryFormAbility extends FormExtensionAbility {
onAddForm(want) {
let formId = want.parameters["ohos.extra.param.key.form_identity"];
let dataObj1 = {
"formId": formId
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
...
};
2、卡片界面
let storage = new LocalStorage();
@Entry(storage)
@Component
struct WidgetCard {
@LocalStorageProp('detail') detail: string = 'init';
@LocalStorageProp('formId') formId: string = '0';
build() {
Column() {
Button('拉至后台')
.margin('20%')
.onClick(() => {
console.info('postCardAction to EntryAbility');
postCardAction(this, {
'action': 'call',
'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
'params': {
'method': 'funA',
'formId': this.formId,
'detail': 'CallFromCard'
}
});
})
Text(`${this.detail}`).margin('20%')
}
.width('100%')
.height('100%')
}
}
let storage = new LocalStorage();
@Entry(storage)
@Component
struct WidgetCard {
@LocalStorageProp('detail') detail: string = 'init';
@LocalStorageProp('formId') formId: string = '0';
build() {
Column() {
Button('拉至后台')
.margin('20%')
.onClick(() => {
console.info('postCardAction to EntryAbility');
postCardAction(this, {
'action': 'call',
'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
'params': {
'method': 'funA',
'formId': this.formId,
'detail': 'CallFromCard'
}
});
})
Text(`${this.detail}`).margin('20%')
}
.width('100%')
.height('100%')
}
}
3、UIAbility界面
import UIAbility from '@ohos.app.ability.UIAbility';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import formInfo from '@ohos.app.form.formInfo';
const MSG_SEND_METHOD: string = 'funA'
// 在收到call事件后会触发callee监听的方法
function FunACall(data) {
// 获取call事件中传递的所有参数
let params = JSON.parse(data.readString())
if (params.formId !== undefined) {
let curFormId = params.formId;
let message = params.detail;
console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
let formData = {
"detail": message
};
let formMsg = formBindingData.createFormBindingData(formData)
formProvider.updateForm(curFormId, formMsg).then((data) => {
console.info('updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('updateForm failed:' + JSON.stringify(error));
})
}
return null;
}
export default class EntryAbility extends UIAbility {
// 如果UIAbility第一次启动,call事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
console.info('Want:' + JSON.stringify(want));
try {
// 监听call事件所需的方法
this.callee.on(MSG_SEND_METHOD, FunACall);
} catch (error) {
console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
}
}
...
}
写在最后
- 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
- 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
- 关注小编,同时可以期待后续文章ing,不定期分享原创知识。
- 更多鸿蒙最新技术知识点,请关注作者博客:https://t.doruo.cn/14DjR1rEY

鸿蒙HarmonyOS实战-Stage模型(开发卡片事件)的更多相关文章
- 最全华为鸿蒙 HarmonyOS 开发资料汇总
开发 本示例基于 OpenHarmony 下的 JavaScript UI 框架,进行项目目录解读,JS FA.常用和自定义组件.用户交互.JS 动画的实现,通过本示例可以基本了解和学习到 JavaS ...
- HTML5实战与剖析之触摸事件(touchstart、touchmove和touchend)(转)
HTML5中新添加了很多事件,但是由于他们的兼容问题不是很理想,应用实战性不是太强,所以在这里基本省略,咱们只分享应用广泛兼容不错的事件,日后随着兼容情况提升以后再陆续添加分享.今天为大家介绍的事件主 ...
- (转)HTML5实战与剖析之触摸事件(touchstart、touchmove和touchend)
HTML5中新添加了很多事件,但是由于他们的兼容问题不是很理想,应用实战性不是太强,所以在这里基本省略,咱们只分享应用广泛兼容不错的事件,日后随着兼容情况提升以后再陆续添加分享.今天为大家介绍的事件主 ...
- 手把手带你体验鸿蒙 harmonyOS
wNlRGd.png 前言 本文已经收录到我的 Github 个人博客,欢迎大佬们光临寒舍: 我的 GIthub 博客 学习导图 image.png 一.为什么要尝鲜 harmonyos? wNlfx ...
- js事件模型与自定义事件
JavaScript 一个最简单的事件模型,需要有事件绑定与触发,还有事件删除. var eventModel = { list: {}, bind: function () { var args = ...
- BI之SSAS完整实战教程2 -- 开发环境介绍及多维数据集数据源准备
上一篇我们已经完成所有的准备工作,现在我们就开始动手,通过接下来的三篇文章创建第一个多维数据集. 传统的维度和多维数据集设计方法主要是基于现有的单源数据集. 在现实世界中,当开发商业智能应用程序时,很 ...
- webpack快速入门——实战技巧:开发和生产并行设置
package.json中,devDependencies和dependencies是不同的 devDependencies:开发依赖 dependencies:生产依赖(线上) 1.安装生产环境的依 ...
- vue.js2.0实战(1):搭建开发环境及构建项目
Vue.js学习系列: vue.js2.0实战(1):搭建开发环境及构建项目 https://my.oschina.net/brillantzhao/blog/1541638 vue.js2.0实战( ...
- 【Android开发VR实战】三.开发一个寻宝类VR游戏TreasureHunt
转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53939303 本文出自[DylanAndroid的博客] [Android开发 ...
- 无人机基于Matlab/Simulink的模型开发(连载一)
"一切可以被控制的对象,都需要被数学量化" 这是笔者从事多年研发工作得出的道理,无论是车辆控制,机器人控制,飞机控制,还是无人机控制,所有和机械运动相关的控制,如果不能被很好的数学 ...
随机推荐
- SQL FOREIGN KEY 约束- 保障表之间关系完整性的关键规则
SQL FOREIGN KEY 约束 SQL FOREIGN KEY 约束用于防止破坏表之间关系的操作.FOREIGN KEY 是一张表中的字段(或字段集合),它引用另一张表中的主键.具有外键的表称为 ...
- docker 应用篇————es[八]
前言 简单介绍一下es镜像. 正文 首先安装一下: elasticSearch. 启动一下: 然后就可以访问了. 使用一下docker stats 然后你就发现了这个docker 容器启动的时候要1. ...
- RestfulApi 学习笔记——内容协商(三)
前言 什么是内容协商呢?是这样的,我们在请求的时候都有两个属性,一个是Content-Type,另一个是accept,这两个什么意思呢? content-type 这个是表示自己传输的是什么内容,就像 ...
- python websocket 参数
websocket中就有建立连接connect.发送消息send等函数可供使用,但是websocket.WebSocketApp将这些都封装好了,只用在实例化的时候传入自定义函数即可,更方便.因此这里 ...
- C内存操作API的实现原理
我们在编写C代码时,会使用两种类型的内存,一种是栈内存,另外一种是堆内存,其中栈内存的申请和释放是由编译器来隐式管理的,我们也称为自动内存,这种变量是最简单而且最常用的,然后就是堆内存,堆的申请和释放 ...
- 《c#高级编程》第3章C#3.0中的更改(五)——扩展方法
C#扩展方法是一种语法,可以为已有的类添加新的实例方法,而无需修改原来的类定义.它的语法形式为: ```csharppublic static void MyExtensionMethod(this ...
- 浅谈sparse vec检索工程化实现
前面我们通过两篇文章: BGE M3-Embedding 模型介绍 和 Sparse稀疏检索介绍与实践 介绍了sparse 稀疏检索,今天我们来看看如何建立一个工程化的系统来实现sparse vec的 ...
- Docker 安装,常用命令
安装Docker 官方所有操作系统安装教程:Install Docker Engine on CentOS | Docker Documentation,其中CentOS安装docker引擎的代码: ...
- Hologres如何支持亿级用户UV计算
简介: 本文将介绍阿里云Hologres如何基于RoaringBitmap进行UV等高复杂度计算的方案,实现亿级用户万级标签亚秒级分析,帮助用户从Kylin平滑迁移到Hologres,实现更实时.开发 ...
- Hologres揭秘:优化COPY,批量导入性能提升5倍+
简介: 揭秘Hologres优化COPY的技术原理,实现批量导入性能提升5倍+ Hologres(中文名交互式分析)是阿里云自研的一站式实时数仓,这个云原生系统融合了实时服务和分析大数据的场景,全面兼 ...