• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 使用call事件拉起指定UIAbility到后台
2
3
4许多应用希望借助卡片的能力,实现和应用在前台时相同的功能。例如音乐卡片,卡片上提供播放、暂停等按钮,点击不同按钮将触发音乐应用的不同功能,进而提高用户的体验。在卡片中使用**postCardAction**接口的call能力,能够将卡片提供方应用的指定的UIAbility拉到后台。同时,call能力提供了调用应用指定方法、传递数据的功能,使应用在后台运行时可以通过卡片上的按钮执行不同的功能。
5
6> **说明:**
7>
8> 本文主要介绍动态卡片的事件开发。对于静态卡片,请参见[FormLink](../reference/apis-arkui/arkui-ts/ts-container-formlink.md)。
9
10## 约束限制
11
12-提供方应用需要具备后台运行权限([ohos.permission.KEEP_BACKGROUND_RUNNING](../security/AccessToken/permissions-for-all.md#ohospermissionkeep_background_running))。
13
14## 开发步骤
15
16通常使用按钮控件来触发call事件,示例代码如下:
17
18
19- 在卡片页面中布局两个按钮,点击其中一个按钮时调用postCardAction向指定UIAbility发送call事件,并在事件内定义需要调用的方法和传递的数据。需要注意的是,method参数为必选参数,且类型需要为string类型,用于触发UIAbility中对应的方法。
20
21  ```ts
22  @Entry
23  @Component
24  struct WidgetEventCallCard {
25    @LocalStorageProp('formId') formId: string = '12400633174999288';
26
27    build() {
28      Column() {
29        Text($r('app.string.WidgetEventCallEntryAbility_desc'))
30          .fontColor('#FFFFFF')
31          .opacity(0.9)
32          .fontSize(14)
33          .margin({ top: '8%', left: '10%' })
34        Row() {
35          Column() {
36            Button() {
37              Text($r('app.string.ButtonA_label'))
38                .fontColor('#45A6F4')
39                .fontSize(12)
40            }
41            .width(120)
42            .height(32)
43            .margin({ top: '20%' })
44            .backgroundColor('#FFFFFF')
45            .borderRadius(16)
46            .onClick(() => {
47              postCardAction(this, {
48                action: 'call',
49                abilityName: 'WidgetEventCallEntryAbility', // 只能跳转到当前应用下的UIAbility
50                params: {
51                  formId: this.formId,
52                  method: 'funA' // 在EntryAbility中调用的方法名
53                }
54              });
55            })
56
57            Button() {
58              Text($r('app.string.ButtonB_label'))
59                .fontColor('#45A6F4')
60                .fontSize(12)
61            }
62            .width(120)
63            .height(32)
64            .margin({ top: '8%', bottom: '15vp' })
65            .backgroundColor('#FFFFFF')
66            .borderRadius(16)
67            .onClick(() => {
68              postCardAction(this, {
69                action: 'call',
70                abilityName: 'WidgetEventCallEntryAbility', // 只能跳转到当前应用下的UIAbility
71                params: {
72                  formId: this.formId,
73                  method: 'funB', // 在EntryAbility中调用的方法名
74                  num: 1 // 需要传递的其他参数
75                }
76              });
77            })
78          }
79        }.width('100%').height('80%')
80        .justifyContent(FlexAlign.Center)
81      }
82      .width('100%')
83      .height('100%')
84      .alignItems(HorizontalAlign.Start)
85      .backgroundImage($r('app.media.CardEvent'))
86      .backgroundImageSize(ImageSize.Cover)
87    }
88  }
89  ```
90
91- 在UIAbility中接收call事件并获取参数,根据传递的method不同,执行不同的方法。其余数据可以通过[readString](../reference/apis-ipc-kit/js-apis-rpc.md#readstring)方法获取。需要注意的是,UIAbility需要onCreate生命周期中监听所需的方法。
92
93  ```ts
94  import type AbilityConstant from '@ohos.app.ability.AbilityConstant';
95  import type Base from '@ohos.base';
96  import hilog from '@ohos.hilog';
97  import promptAction from '@ohos.promptAction';
98  import type rpc from '@ohos.rpc';
99  import UIAbility from '@ohos.app.ability.UIAbility';
100  import type Want from '@ohos.app.ability.Want';
101
102  const TAG: string = 'WidgetEventCallEntryAbility';
103  const DOMAIN_NUMBER: number = 0xFF00;
104  const CONST_NUMBER_1: number = 1;
105  const CONST_NUMBER_2: number = 2;
106
107  class MyParcelable implements rpc.Parcelable {
108    num: number;
109    str: string;
110
111    constructor(num: number, str: string) {
112      this.num = num;
113      this.str = str;
114    }
115
116    marshalling(messageSequence: rpc.MessageSequence): boolean {
117      messageSequence.writeInt(this.num);
118      messageSequence.writeString(this.str);
119      return true;
120    }
121
122    unmarshalling(messageSequence: rpc.MessageSequence): boolean {
123      this.num = messageSequence.readInt();
124      this.str = messageSequence.readString();
125      return true;
126    }
127  }
128
129  export default class WidgetEventCallEntryAbility extends UIAbility {
130    // 如果UIAbility第一次启动,在收到call事件后会触发onCreate生命周期回调
131    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
132      try {
133        // 监听call事件所需的方法
134        this.callee.on('funA', (data: rpc.MessageSequence) => {
135          // 获取call事件中传递的所有参数
136          hilog.info(DOMAIN_NUMBER, TAG, `FunACall param:  ${JSON.stringify(data.readString())}`);
137          promptAction.showToast({
138            message: 'FunACall param:' + JSON.stringify(data.readString())
139          });
140          return new MyParcelable(CONST_NUMBER_1, 'aaa');
141        });
142        this.callee.on('funB', (data: rpc.MessageSequence) => {
143          // 获取call事件中传递的所有参数
144          hilog.info(DOMAIN_NUMBER, TAG, `FunBCall param:  ${JSON.stringify(data.readString())}`);
145          promptAction.showToast({
146            message: 'FunBCall param:' + JSON.stringify(data.readString())
147          });
148          return new MyParcelable(CONST_NUMBER_2, 'bbb');
149        });
150      } catch (err) {
151        hilog.error(DOMAIN_NUMBER, TAG, `Failed to register callee on. Cause: ${JSON.stringify(err as Base.BusinessError)}`);
152      };
153    }
154
155    // 进程退出时,解除监听
156    onDestroy(): void | Promise<void> {
157      try {
158        this.callee.off('funA');
159        this.callee.off('funB');
160      } catch (err) {
161        hilog.error(DOMAIN_NUMBER, TAG, `Failed to register callee off. Cause: ${JSON.stringify(err as Base.BusinessError)}`);
162      };
163    }
164  }
165  ```
166