1# 卡片代理刷新
2
3卡片代理刷新是一种通过系统应用刷新卡片的机制。卡片提供方不在运行时,仍然可以通过开启了数据共享能力的系统应用完成卡片数据的更新。
4
5## 实现原理
6
7**图1** 代理刷新运行原理
8![UpdateWidgetByProxyPrinciple](figures/UpdateWidgetByProxyPrinciple.png)
9
10如图1,与[ArkTS卡片实现原理图](arkts-ui-widget-working-principles.md#实现原理)相比,卡片代理刷新原理新增了数据管理服务和数据提供方。
11
12- 数据管理服务:该场景下主要提供了多应用间的数据共享的机制。
13- 数据提供方(仅支持系统应用):系统应用作为数据提供方,需要开启数据共享能力,同时需要自定义`key + subscriberId`作为共享数据的标识。
14
15> **说明:**
16>
17> 只有系统提供了作为数据提供方的应用,同时提供公开可获得的共享数据标识,才能正常使用该特性。
18
19卡片提供方处理流程(图中蓝色箭头):
20
211. 卡片提供方在卡片提供方的配置文件`form_config.json`中配置`dataProxyEnabled`字段为`true`,以开启卡片代理刷新功能。
22> **说明:**
23>
24> 卡片代理刷新开启后,[定时刷新](arkts-ui-widget-update-by-time.md)和[下次刷新](arkts-ui-widget-update-by-time.md)失效。
25
262. 卡片提供方在[onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform)回调中,把数据提供方定义的`key + subscriberId`返回给卡片管理服务。
27
283. 卡片管理服务解析卡片提供方的订阅信息,并向数据管理服务注册订阅实例。
29
30卡片代理刷新运行流程(图中红色箭头):
31
321. 数据提供方以`key + subscriberId`作为数据的标识,将数据存储到数据库。
332. 数据管理服务感知到数据库变化,将新的数据发布给当前注册的所有订阅实例。
343. 卡片管理服务从订阅实例中解析出数据,发送给卡片渲染服务。
354. 卡片渲染服务运行卡片页面代码widgets.abcwidgets.abc按新数据进行渲染,并将渲染后的数据发送至卡片使用方对应的<!--Del-->[<!--DelEnd-->卡片组件<!--Del-->](../reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md)<!--DelEnd-->。
36
37数据提供方提供的共享数据有两种类型:
38
39- 过程数据,不会一直存储,有老化期,所有应用都可以订阅。
40
41- 持久化数据,仅系统应用可以订阅。
42
43相应的卡片代理刷新配置有所不同,下面分别介绍具体开发方式。
44<!--Del-->
45## 数据提供方开发步骤
46
47参考[数据管理](../database/share-data-by-silent-access.md)开发指南。
48<!--DelEnd-->
49## 卡片提供方开发步骤(过程数据)
50
51- 配置form_config.json文件中的`dataProxyEnabled`字段为`true`,以启用卡片代理刷新功能,当订阅的过程数据更新时,系统会自动更新卡片数据。
52  ```json
53  {
54    "forms": [
55      {
56        "name": "WidgetProcessData",
57        "description": "$string:ProcessDataEntryAbility_desc",
58        "src": "./ets/widgetprocessdata/pages/WidgetProcessDataCard.ets",
59        "uiSyntax": "arkts",
60        "window": {
61          "designWidth": 720,
62          "autoDesignWidth": true
63        },
64        "colorMode": "auto",
65        "isDefault": true,
66        "updateEnabled": true,
67        "scheduledUpdateTime": "10:30",
68        "defaultDimension": "2*2",
69        "supportDimensions": [
70          "2*2"
71        ],
72        "dataProxyEnabled": true
73      }
74    ]
75  }
76  ```
77
78- 在[onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform)回调中配置订阅信息[proxyData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#proxydata10),并通过[formBinding](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#formbindingdata)返回给卡片管理服务。示例中将key设置为"datashareproxy://com.samples.widgetupdatebyproxy/weather",subscriberId设置为"11"。
79  > **说明:**
80  >
81  > key可以是uri也可以是简单字符串,subscriberId默认值为当前formId,实际取值都依赖于数据发布方的定义。
82  ```ts
83  import { formBindingData, FormExtensionAbility } from '@kit.FormKit';
84  import { Want } from '@kit.AbilityKit';
85  import { hilog } from '@kit.PerformanceAnalysisKit';
86
87  const TAG: string = 'ProcessDataFormAbility';
88  const DOMAIN_NUMBER: number = 0xFF00;
89
90  export default class ProcessDataFormAbility extends FormExtensionAbility {
91    onAddForm(want: Want): formBindingData.FormBindingData {
92      let formData: Record<string, Object> = {};
93      let proxies: formBindingData.ProxyData[] = [
94        {
95          key: 'datashareproxy://com.samples.widgetupdatebyproxy/weather',
96          subscriberId: '11'
97        }
98      ];
99      let formBinding = formBindingData.createFormBindingData(formData);
100      formBinding.proxies = proxies;
101      hilog.info(DOMAIN_NUMBER, TAG, 'onAddForm');
102      return formBinding;
103    }
104  }
105  ```
106
107- 在[卡片页面文件](arkts-ui-widget-creation.md)中,通过LocalStorage变量获取订阅到的数据,LocalStorage绑定了一个字符串,以key:value的键值对格式来刷新卡片订阅数据,其中key必须与卡片提供方订阅的key保持一致。示例中,通过'city'获取订阅的数据,并在Text组件显示。
108  ```ts
109  let storageProcess = new LocalStorage();
110
111  @Entry(storageProcess)
112  @Component
113  struct WidgetProcessDataCard {
114    @LocalStorageProp('datashareproxy://com.samples.widgetupdatebyproxy/weather') city: ResourceStr = $r('app.string.loading');
115
116    build() {
117      Column() {
118        Column() {
119          Text(this.city)
120            .fontColor('#FFFFFF')
121            .opacity(0.9)
122            .fontSize(14)
123            .margin({ top: '8%', left: '10%' })
124        }.width('100%')
125        .alignItems(HorizontalAlign.Start)
126      }.width('100%').height('100%')
127      .backgroundImage($r('app.media.CardEvent'))
128      .backgroundImageSize(ImageSize.Cover)
129    }
130  }
131  ```
132
133## 卡片提供方开发步骤(持久化数据,仅对系统应用开放)
134- 配置form_config.json文件中的`dataProxyEnabled`字段为`true`,以启用卡片代理刷新功能。
135  ```json
136  {
137    "forms": [
138      {
139        "name": "WidgetPersistentData",
140        "description": "This is a service widget update by proxy using persistent data.",
141        "src": "./ets/widgetpersistentdata/pages/WidgetPersistentDataCard.ets",
142        "uiSyntax": "arkts",
143        "window": {
144          "designWidth": 720,
145          "autoDesignWidth": true
146        },
147        "colorMode": "auto",
148        "isDefault": true,
149        "updateEnabled": true,
150        "scheduledUpdateTime": "10:30",
151        "updateDuration": 1,
152        "defaultDimension": "2*2",
153        "supportDimensions": [
154          "2*2"
155        ],
156        "dataProxyEnabled": true
157      }
158  ]
159  }
160  ```
161
162- 在[onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform)回调中添加订阅模板<!--Del-->[<!--DelEnd-->addTemplate<!--Del-->](../reference/apis-arkdata/js-apis-data-dataShare-sys.md#addtemplate10)<!--DelEnd-->,通过模板谓词告诉数据库订阅的数据条件。然后配置订阅信息[proxyData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#proxydata10),并通过[FormBindingData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#formbindingdata)返回给卡片管理服务。示例中将谓词设置为`"list" : "select type from TBL00 limit 0,1"`,表示从TBL00数据库中获取type列的第一条数据,数据将会以`{"list":[{"type":"value0"}]}`格式返回到卡片页面代码widgets.abc中。当订阅的持久化数据更新时,系统会自动更新卡片数据。
163
164  > **说明:**
165  >
166  > - key的取值是uri,依赖于数据发布方定义。
167  > - subscriberId可自定义,addTemplate中的subscriberId参数与proxies.subscriberId保持一致即可。
168  ```ts
169  import { formBindingData, FormExtensionAbility } from '@kit.FormKit';
170  import { Want } from '@kit.AbilityKit';
171  import { dataShare } from '@kit.ArkData';
172
173  export default class PersistentDataFormAbility extends FormExtensionAbility {
174    onAddForm(want: Want): formBindingData.FormBindingData {
175      let subscriberId = '111';
176      let template: dataShare.Template = {
177        predicates: {
178          'list': `select type from TBL00 where cityId = ${subscriberId}`
179        },
180        scheduler: ''
181      };
182      dataShare.createDataShareHelper(this.context, 'datashareproxy://com.samples.widgetupdatebyproxy', {
183        isProxy: true
184      }).then((data) => {
185        let dataShareHelper = data;
186        dataShareHelper.addTemplate('datashareproxy://com.samples.widgetupdatebyproxy/test', subscriberId, template);
187      });
188      let formData: Record<string, Object> = {};
189      let proxies: formBindingData.ProxyData[] = [
190        {
191          key: 'datashareproxy://com.samples.widgetupdatebyproxy/test',
192          subscriberId: subscriberId
193        }
194      ];
195
196      let formBinding: formBindingData.FormBindingData = {
197        data: JSON.stringify(formData),
198        proxies: proxies
199      };
200      return formBinding;
201    }
202  }
203  ```
204
205- 在[卡片页面文件](arkts-ui-widget-creation.md)中,通过LocalStorage变量获取订阅到的数据,LocalStorage绑定了一个字符串,以key:value的键值对格式来刷新卡片订阅数据,其中key必须与卡片提供方订阅的key保持一致。示例中,通过'list'获取订阅的数据,并把第一个元素的值显示在Text组件上。
206  ```ts
207  let storagePersis = new LocalStorage();
208
209  @Entry(storagePersis)
210  @Component
211  struct WidgetPersistentDataCard {
212    readonly FULL_WIDTH_PERCENT: string = '100%';
213    readonly FULL_HEIGHT_PERCENT: string = '100%';
214    @LocalStorageProp('list') list: Record<string, string>[] = [{ 'type': 'a' }];
215
216    build() {
217      Column() {
218        Column() {
219          Text((this.list[0]['type']))
220            .fontColor('#FFFFFF')
221            .opacity(0.9)
222            .fontSize(14)
223            .margin({ top: '8%', left: '10%' })
224        }.width('100%')
225        .alignItems(HorizontalAlign.Start)
226      }.width(this.FULL_WIDTH_PERCENT).height(this.FULL_HEIGHT_PERCENT)
227      .backgroundImage($r('app.media.CardEvent'))
228      .backgroundImageSize(ImageSize.Cover)
229    }
230  }
231  ```
232<!--Del-->
233## 相关实例
234
235针对卡片代理开发,有以下相关实例可供参考:
236
237- [应用主动添加数据代理卡片到桌面(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Widget/RequestAddForm)
238<!--DelEnd-->