经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 鸿蒙 » 查看文章
鸿蒙HarmonyOS实战-Stage模型(开发卡片事件)
来源:cnblogs  作者:蜀道山QAQ  时间:2024/5/21 8:45:25  对本文有异议

??一、开发卡片事件

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

??1.卡片事件能力说明

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

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

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

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

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

image

??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. }

image

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. };

image

??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. }

image

??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. }
  29. let storage = new LocalStorage();
  30. @Entry(storage)
  31. @Component
  32. struct WidgetCard {
  33. @LocalStorageProp('detail') detail: string = 'init';
  34. @LocalStorageProp('formId') formId: string = '0';
  35. build() {
  36. Column() {
  37. Button('拉至后台')
  38. .margin('20%')
  39. .onClick(() => {
  40. console.info('postCardAction to EntryAbility');
  41. postCardAction(this, {
  42. 'action': 'call',
  43. 'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
  44. 'params': {
  45. 'method': 'funA',
  46. 'formId': this.formId,
  47. 'detail': 'CallFromCard'
  48. }
  49. });
  50. })
  51. Text(`${this.detail}`).margin('20%')
  52. }
  53. .width('100%')
  54. .height('100%')
  55. }
  56. }

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??,不定期分享原创知识。
  • 更多鸿蒙最新技术知识点,请关注作者博客:https://t.doruo.cn/14DjR1rEY

image

原文链接:https://www.cnblogs.com/shudaoshan/p/18203026

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号