首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

鸿蒙HarmonyOS实战-Stage模型(开发卡片事件)

  • 25-02-22 03:40
  • 2836
  • 12391
blog.csdn.net

 一、开发卡片事件

HarmonyOS元服务卡片页面(Metaservice Card Page)是指在HarmonyOS系统中,用于展示元服务的页面界面。元服务是指一组提供特定功能或服务的组件,例如天气服务、音乐播放服务等。元服务卡片页面可以显示元服务的相关信息和操作选项,用户可以通过点击卡片页面上的按钮或交互元素来使用相关的元服务功能。元服务卡片页面提供了一种快速访问和使用元服务的方式,方便用户进行各种操作和任务。

1.卡片事件能力说明

postCardAction()接口是ArkTS卡片中用于实现卡片内部和提供方应用间交互的方法。目前这个接口支持三种类型的事件:router、message和call,并且仅在卡片中可以调用。

  • router类型的事件可以用来执行页面跳转或路由切换的操作。通过指定目标路由和传递参数,可以实现页面之间的跳转或路由切换。

  • message类型的事件用于发送消息或通知给提供方应用。可以通过指定目标应用和消息内容,向提供方应用发送消息或通知。

  • call类型的事件用于调用提供方应用的函数或方法。可以通过指定目标应用、要调用的函数或方法名以及传递的参数,调用提供方应用中的函数或方法。

postCardAction()接口仅在卡片内部可以调用,无法在提供方应用中直接调用。这个接口提供了卡片和提供方应用之间进行交互的方式,可以实现卡片的功能扩展和与提供方应用的数据交互。

在这里插入图片描述

2.使用router事件跳转到指定UIAbility

1、元服务界面

  1. @Entry
  2. @Component
  3. struct WidgetCard {
  4. build() {
  5. Column() {
  6. Button('功能A')
  7. .margin('20%')
  8. .onClick(() => {
  9. console.info('Jump to EntryAbility funA');
  10. postCardAction(this, {
  11. 'action': 'router',
  12. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  13. 'params': {
  14. 'targetPage': 'funA' // 在EntryAbility中处理这个信息
  15. }
  16. });
  17. })
  18. Button('功能B')
  19. .margin('20%')
  20. .onClick(() => {
  21. console.info('Jump to EntryAbility funB');
  22. postCardAction(this, {
  23. 'action': 'router',
  24. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  25. 'params': {
  26. 'targetPage': 'funB' // 在EntryAbility中处理这个信息
  27. }
  28. });
  29. })
  30. }
  31. .width('100%')
  32. .height('100%')
  33. }
  34. }

在这里插入图片描述

2、UIAbility接收参数

  1. import UIAbility from '@ohos.app.ability.UIAbility';
  2. import window from '@ohos.window';
  3. let selectPage = "";
  4. let currentWindowStage = null;
  5. export default class CameraAbility extends UIAbility {
  6. // 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
  7. onCreate(want, launchParam) {
  8. // 获取router事件中传递的targetPage参数
  9. console.info("onCreate want:" + JSON.stringify(want));
  10. if (want.parameters.params !== undefined) {
  11. let params = JSON.parse(want.parameters.params);
  12. console.info("onCreate router targetPage:" + params.targetPage);
  13. selectPage = params.targetPage;
  14. }
  15. }
  16. // 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
  17. onNewWant(want, launchParam) {
  18. console.info("onNewWant want:" + JSON.stringify(want));
  19. if (want.parameters.params !== undefined) {
  20. let params = JSON.parse(want.parameters.params);
  21. console.info("onNewWant router targetPage:" + params.targetPage);
  22. selectPage = params.targetPage;
  23. }
  24. if (currentWindowStage != null) {
  25. this.onWindowStageCreate(currentWindowStage);
  26. }
  27. }
  28. onWindowStageCreate(windowStage: window.WindowStage) {
  29. let targetPage;
  30. // 根据传递的targetPage不同,选择拉起不同的页面
  31. switch (selectPage) {
  32. case 'funA':
  33. targetPage = 'pages/FunA';
  34. break;
  35. case 'funB':
  36. targetPage = 'pages/FunB';
  37. break;
  38. default:
  39. targetPage = 'pages/Index';
  40. }
  41. if (currentWindowStage === null) {
  42. currentWindowStage = windowStage;
  43. }
  44. windowStage.loadContent(targetPage, (err, data) => {
  45. if (err && err.code) {
  46. console.info('Failed to load the content. Cause: %{public}s', JSON.stringify(err));
  47. return;
  48. }
  49. });
  50. }
  51. };

在这里插入图片描述

3.使用call事件拉起指定UIAbility到后台

1、元服务界面

  1. @Entry
  2. @Component
  3. struct WidgetCard {
  4. build() {
  5. Column() {
  6. Button('功能A')
  7. .margin('20%')
  8. .onClick(() => {
  9. console.info('call EntryAbility funA');
  10. postCardAction(this, {
  11. 'action': 'call',
  12. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  13. 'params': {
  14. 'method': 'funA' // 在EntryAbility中调用的方法名
  15. }
  16. });
  17. })
  18. Button('功能B')
  19. .margin('20%')
  20. .onClick(() => {
  21. console.info('call EntryAbility funB');
  22. postCardAction(this, {
  23. 'action': 'call',
  24. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  25. 'params': {
  26. 'method': 'funB', // 在EntryAbility中调用的方法名
  27. 'num': 1 // 需要传递的其他参数
  28. }
  29. });
  30. })
  31. }
  32. .width('100%')
  33. .height('100%')
  34. }
  35. }

2、UIAbility接收参数

  1. import UIAbility from '@ohos.app.ability.UIAbility';
  2. function FunACall(data) {
  3. // 获取call事件中传递的所有参数
  4. console.log('FunACall param:' + JSON.stringify(data.readString()));
  5. return null;
  6. }
  7. function FunBCall(data) {
  8. console.log('FunACall param:' + JSON.stringify(data.readString()));
  9. return null;
  10. }
  11. export default class CameraAbility extends UIAbility {
  12. // 如果UIAbility第一次启动,在收到call事件后会触发onCreate生命周期回调
  13. onCreate(want, launchParam) {
  14. try {
  15. // 监听call事件所需的方法
  16. this.callee.on('funA', FunACall);
  17. this.callee.on('funB', FunBCall);
  18. } catch (error) {
  19. console.log('register failed with error. Cause: ' + JSON.stringify(error));
  20. }
  21. }
  22. // 进程退出时,解除监听
  23. onDestroy() {
  24. try {
  25. this.callee.off('funA');
  26. this.callee.off('funB');
  27. } catch (error) {
  28. console.log('register failed with error. Cause: ' + JSON.stringify(error));
  29. }
  30. }
  31. };

不截图同上

4.通过message事件刷新卡片内容

1、卡片页面

  1. let storage = new LocalStorage();
  2. @Entry(storage)
  3. @Component
  4. struct WidgetCard {
  5. @LocalStorageProp('title') title: string = 'init';
  6. @LocalStorageProp('detail') detail: string = 'init';
  7. build() {
  8. Column() {
  9. Button('刷新')
  10. .onClick(() => {
  11. postCardAction(this, {
  12. 'action': 'message',
  13. 'params': {
  14. 'msgTest': 'messageEvent'
  15. }
  16. });
  17. })
  18. Text(`${this.title}`)
  19. Text(`${this.detail}`)
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

2、卡片FormExtensionAbility

  1. import formBindingData from '@ohos.app.form.formBindingData';
  2. import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
  3. import formProvider from '@ohos.app.form.formProvider';
  4. export default class EntryFormAbility extends FormExtensionAbility {
  5. onFormEvent(formId, message) {
  6. // Called when a specified message event defined by the form provider is triggered.
  7. console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);
  8. let formData = {
  9. 'title': 'Title Update Success.', // 和卡片布局中对应
  10. 'detail': 'Detail Update Success.', // 和卡片布局中对应
  11. };
  12. let formInfo = formBindingData.createFormBindingData(formData)
  13. formProvider.updateForm(formId, formInfo).then((data) => {
  14. console.info('FormAbility updateForm success.' + JSON.stringify(data));
  15. }).catch((error) => {
  16. console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
  17. })
  18. }
  19. }

在这里插入图片描述

5.通过router或call事件刷新卡片内容

?5.1 router

1、卡片

  1. let storage = new LocalStorage();
  2. @Entry(storage)
  3. @Component
  4. struct WidgetCard {
  5. @LocalStorageProp('detail') detail: string = 'init';
  6. build() {
  7. Column() {
  8. Button('跳转')
  9. .margin('20%')
  10. .onClick(() => {
  11. console.info('postCardAction to EntryAbility');
  12. postCardAction(this, {
  13. 'action': 'router',
  14. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  15. 'params': {
  16. 'detail': 'RouterFromCard'
  17. }
  18. });
  19. })
  20. Text(`${this.detail}`).margin('20%')
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

2、UIAbility

  1. import UIAbility from '@ohos.app.ability.UIAbility';
  2. import formBindingData from '@ohos.app.form.formBindingData';
  3. import formProvider from '@ohos.app.form.formProvider';
  4. import formInfo from '@ohos.app.form.formInfo';
  5. export default class EntryAbility extends UIAbility {
  6. // 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
  7. onCreate(want, launchParam) {
  8. console.info('Want:' + JSON.stringify(want));
  9. if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
  10. let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
  11. let message = JSON.parse(want.parameters.params).detail;
  12. console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
  13. let formData = {
  14. "detail": message + ': onCreate UIAbility.', // 和卡片布局中对应
  15. };
  16. let formMsg = formBindingData.createFormBindingData(formData)
  17. formProvider.updateForm(curFormId, formMsg).then((data) => {
  18. console.info('updateForm success.' + JSON.stringify(data));
  19. }).catch((error) => {
  20. console.error('updateForm failed:' + JSON.stringify(error));
  21. })
  22. }
  23. }
  24. // 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
  25. onNewWant(want, launchParam) {
  26. console.info('onNewWant Want:' + JSON.stringify(want));
  27. if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
  28. let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
  29. let message = JSON.parse(want.parameters.params).detail;
  30. console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
  31. let formData = {
  32. "detail": message + ': onNewWant UIAbility.', // 和卡片布局中对应
  33. };
  34. let formMsg = formBindingData.createFormBindingData(formData)
  35. formProvider.updateForm(curFormId, formMsg).then((data) => {
  36. console.info('updateForm success.' + JSON.stringify(data));
  37. }).catch((error) => {
  38. console.error('updateForm failed:' + JSON.stringify(error));
  39. })
  40. }
  41. }
  42. ...
  43. }

?5.2 call

1、在使用postCardAction接口的call事件时,需要在FormExtensionAbility中的onAddForm生命周期回调中更新formId。

  1. import formBindingData from '@ohos.app.form.formBindingData';
  2. import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
  3. export default class EntryFormAbility extends FormExtensionAbility {
  4. onAddForm(want) {
  5. let formId = want.parameters["ohos.extra.param.key.form_identity"];
  6. let dataObj1 = {
  7. "formId": formId
  8. };
  9. let obj1 = formBindingData.createFormBindingData(dataObj1);
  10. return obj1;
  11. }
  12. ...
  13. };

2、卡片界面

  1. let storage = new LocalStorage();
  2. @Entry(storage)
  3. @Component
  4. struct WidgetCard {
  5. @LocalStorageProp('detail') detail: string = 'init';
  6. @LocalStorageProp('formId') formId: string = '0';
  7. build() {
  8. Column() {
  9. Button('拉至后台')
  10. .margin('20%')
  11. .onClick(() => {
  12. console.info('postCardAction to EntryAbility');
  13. postCardAction(this, {
  14. 'action': 'call',
  15. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  16. 'params': {
  17. 'method': 'funA',
  18. 'formId': this.formId,
  19. 'detail': 'CallFromCard'
  20. }
  21. });
  22. })
  23. Text(`${this.detail}`).margin('20%')
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }
  1. let storage = new LocalStorage();
  2. @Entry(storage)
  3. @Component
  4. struct WidgetCard {
  5. @LocalStorageProp('detail') detail: string = 'init';
  6. @LocalStorageProp('formId') formId: string = '0';
  7. build() {
  8. Column() {
  9. Button('拉至后台')
  10. .margin('20%')
  11. .onClick(() => {
  12. console.info('postCardAction to EntryAbility');
  13. postCardAction(this, {
  14. 'action': 'call',
  15. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  16. 'params': {
  17. 'method': 'funA',
  18. 'formId': this.formId,
  19. 'detail': 'CallFromCard'
  20. }
  21. });
  22. })
  23. Text(`${this.detail}`).margin('20%')
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

3、UIAbility界面

  1. import UIAbility from '@ohos.app.ability.UIAbility';
  2. import formBindingData from '@ohos.app.form.formBindingData';
  3. import formProvider from '@ohos.app.form.formProvider';
  4. import formInfo from '@ohos.app.form.formInfo';
  5. const MSG_SEND_METHOD: string = 'funA'
  6. // 在收到call事件后会触发callee监听的方法
  7. function FunACall(data) {
  8. // 获取call事件中传递的所有参数
  9. let params = JSON.parse(data.readString())
  10. if (params.formId !== undefined) {
  11. let curFormId = params.formId;
  12. let message = params.detail;
  13. console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
  14. let formData = {
  15. "detail": message
  16. };
  17. let formMsg = formBindingData.createFormBindingData(formData)
  18. formProvider.updateForm(curFormId, formMsg).then((data) => {
  19. console.info('updateForm success.' + JSON.stringify(data));
  20. }).catch((error) => {
  21. console.error('updateForm failed:' + JSON.stringify(error));
  22. })
  23. }
  24. return null;
  25. }
  26. export default class EntryAbility extends UIAbility {
  27. // 如果UIAbility第一次启动,call事件后会触发onCreate生命周期回调
  28. onCreate(want, launchParam) {
  29. console.info('Want:' + JSON.stringify(want));
  30. try {
  31. // 监听call事件所需的方法
  32. this.callee.on(MSG_SEND_METHOD, FunACall);
  33. } catch (error) {
  34. console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
  35. }
  36. }
  37. ...
  38. }

 ?写在最后

  • 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注小编,同时可以期待后续文章ing?,不定期分享原创知识。
  • 想要获取更多完整鸿蒙最新VIP学习资料,请点击→全套鸿蒙HarmonyOS学习资料
  • 或者关注小编后私信回复【666】也可获取资料哦~~

最新鸿蒙Next全套学习资料请扫码
微信名片
注:本文转载自blog.csdn.net的蜀道山QAQ的文章"https://blog.csdn.net/shudaoshanQAQ/article/details/135479965"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top