• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 拉起卡片提供方的UIAbility到后台(call事件)
2
3
4许多应用希望借助卡片的能力,实现和应用在前台时相同的功能。例如音乐卡片,卡片上提供播放、暂停等按钮,点击不同按钮将触发音乐应用的不同功能,进而提高用户的体验。在卡片中使用[postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction)接口的call能力,能够将卡片提供方应用的指定的UIAbility拉到后台。同时,call能力提供了调用应用指定方法、传递数据的功能,使应用在后台运行时可以通过卡片上的按钮执行不同的功能。
5
6> **说明:**
7>
8> 本文主要介绍动态卡片的事件开发。对于静态卡片,请参见[FormLink](../reference/apis-arkui/arkui-ts/ts-container-formlink.md)。
9
10## 开发步骤
111. 创建动态卡片
12
13   新建一个名为WidgetEventCall的ArkTs动态卡片。
14
152. 页面布局代码实现
16
17   在卡片页面中布局两个按钮,点击按钮A或按钮B,会调用postCardAction向指定UIAbility发送call事件,在call事件内定义了需要调用的方法。按钮A和按钮B分别对应调用funA、funB方法,其中funA携带了formID参数,funB携带了formID和num参数,开发过程中请根据实际需要传参。
18注意:postCardAction中的method参数为必填参数,用于标识需要调用的方法名称,与步骤3中UIAbility监听的方法一致,其他参数为非必填。
19   ```ts
20    //src/main/ets/widgeteventcallcard/pages/WidgetEventCall.ets
21    @Entry
22    @Component
23    struct WidgetEventCall {
24      @LocalStorageProp('formId') formId: string = '12400633174999288';
25      private funA: string = '按钮A';
26      private funB: string = '按钮B';
27
28      build() {
29        RelativeContainer() {
30          Button(this.funA)
31          .id('funA__')
32          .fontSize($r('app.float.page_text_font_size'))
33          .fontWeight(FontWeight.Bold)
34          .alignRules({
35            center: { anchor: '__container__', align: VerticalAlign.Center },
36            middle: { anchor: '__container__', align: HorizontalAlign.Center }
37          })
38          .onClick(() => {
39            postCardAction(this, {
40              action: 'call',
41              // 只能跳转到当前应用下的UIAbility,与module.json5中定义保持一致
42              abilityName: 'WidgetEventCallEntryAbility',
43              params: {
44                formId: this.formId,
45                // 需要调用的方法名称
46                method: 'funA'
47              }
48            });
49          })
50          Button(this.funB)
51          .id('funB__')
52          .fontSize($r('app.float.page_text_font_size'))
53          .fontWeight(FontWeight.Bold)
54          .margin({ top: 10 })
55          .alignRules({
56            top: { anchor: 'funA__', align: VerticalAlign.Bottom },
57            middle: { anchor: '__container__', align: HorizontalAlign.Center }
58          })
59          .onClick(() => {
60            postCardAction(this, {
61            action: 'call',
62            abilityName: 'WidgetEventCallEntryAbility',
63            params: {
64              formId: this.formId,
65              // 需要调用的方法名称
66              method: 'funB',
67              num: 1
68            }
69          });
70        })
71      }
72      .height('100%')
73      .width('100%')
74      }
75    }
76    ```
773. 创建指定的UIAbility
78
79   在UIAbility中监听call事件,根据监听到的method参数中的方法名称调用对应方法,并通过[rpc.Parcelable](../reference/apis-ipc-kit/js-apis-rpc.md#parcelable9)获取参数。注意:UIAbility中监听的方法与步骤2中调用的方法需保持一致。
80    ```ts
81    //src/main/ets/widgeteventcallcard/WidgetEventCallEntryAbility/WidgetEventCallEntryAbility.ets
82    import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
83    import { BusinessError } from '@kit.BasicServicesKit';
84    import { rpc } from '@kit.IPCKit';
85    import { hilog } from '@kit.PerformanceAnalysisKit';
86
87    const TAG: string = 'WidgetEventCallEntryAbility';
88    const DOMAIN_NUMBER: number = 0xFF00;
89    const CONST_NUMBER_1: number = 1;
90    const CONST_NUMBER_2: number = 2;
91
92    // rpc通信返回类型的实现,用于rpc通信数据序列化和反序列化
93    class MyParcelable implements rpc.Parcelable {
94      num: number;
95      str: string;
96
97      constructor(num: number, str: string) {
98        this.num = num;
99        this.str = str;
100      }
101
102      marshalling(messageSequence: rpc.MessageSequence): boolean {
103        messageSequence.writeInt(this.num);
104        messageSequence.writeString(this.str);
105        return true;
106      }
107
108      unmarshalling(messageSequence: rpc.MessageSequence): boolean {
109        this.num = messageSequence.readInt();
110        this.str = messageSequence.readString();
111          return true;
112      }
113    }
114
115    export default class WidgetEventCallEntryAbility extends UIAbility {
116      // 如果UIAbility启动,在收到call事件后会触发onCreate生命周期回调
117      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
118        try {
119          // 监听call事件所需的方法并调用
120          this.callee.on('funA', (data: rpc.MessageSequence) => {
121            // 获取call事件中传递的所有参数
122            hilog.info(DOMAIN_NUMBER, TAG, `FunACall param:  ${JSON.stringify(data.readString())}`);
123            return new MyParcelable(CONST_NUMBER_1, 'aaa');
124          });
125          this.callee.on('funB', (data: rpc.MessageSequence) => {
126            // 获取call事件中传递的所有参数
127            hilog.info(DOMAIN_NUMBER, TAG, `FunBCall param:  ${JSON.stringify(data.readString())}`);
128            return new MyParcelable(CONST_NUMBER_2, 'bbb');
129          });
130        } catch (err) {
131          hilog.error(DOMAIN_NUMBER, TAG, `Failed to register callee on. Cause: ${JSON.stringify(err as BusinessError)}`);
132        }
133      }
134
135      // 进程退出时,解除监听
136      onDestroy(): void | Promise<void> {
137        try {
138          this.callee.off('funA');
139          this.callee.off('funB');
140        } catch (err) {
141          hilog.error(DOMAIN_NUMBER, TAG, `Failed to register callee off. Cause: ${JSON.stringify(err as BusinessError)}`);
142        }
143      }
144    }
145    ```
1464. 配置后台运行权限
147
148   call事件存在约束限制,卡片提供方应用需要在module.json5下添加后台运行权限([ohos.permission.KEEP_BACKGROUND_RUNNING](../security/AccessToken/permissions-for-all.md#ohospermissionkeep_background_running))。
149    ```ts
150    //src/main/module.json5
151    "requestPermissions":[
152       {
153         "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
154       }
155     ]
156    ```
1575. 配置指定的UIAbility
158
159module.json5的abilities数组内添加WidgetEventCallEntryAbility对应的配置信息。
160    ```ts
161    //src/main/module.json5
162   "abilities": [
163     {
164       "name": 'WidgetEventCallEntryAbility',
165       "srcEntry": './ets/widgeteventcallcard/WidgetEventCallEntryAbility/WidgetEventCallEntryAbility.ets',
166       "description": '$string:WidgetEventCallCard_desc',
167       "icon": "$media:app_icon",
168       "label": "$string:WidgetEventCallCard_label",
169       "startWindowIcon": "$media:app_icon",
170       "startWindowBackground": "$color:start_window_background"
171     }
172   ]
173    ```