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

2024-01-25 12:21 更新

许多应用希望借助卡片的能力,实现和应用在前台时相同的功能。例如音乐卡片,卡片上提供播放、暂停等按钮,点击不同按钮将触发音乐应用的不同功能,进而提高用户的体验。在卡片中使用postCardAction接口的call能力,能够将卡片提供方应用的指定UIAbility拉到后台。同时,call能力提供了调用应用指定方法、传递数据的功能,使应用在后台运行时可以通过卡片上的按钮执行不同的功能。

通常使用按钮控件来触发call事件,示例代码如下:

  • 在卡片页面中布局两个按钮,点击其中一个按钮时调用postCardAction向指定UIAbility发送call事件,并在事件内定义需要调用的方法和传递的数据。需要注意的是,method参数为必选参数,且类型需要为string类型,用于触发UIAbility中对应的方法。
    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. }
  • 在UIAbility中接收call事件并获取参数,根据传递的method不同,执行不同的方法。其余数据可以通过readString的方式获取。需要注意的是,UIAbility需要onCreate生命周期中监听所需的方法。
    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. };
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号