• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.data.dataShare (DataShare)
2
3The **DataShare** module allows an application to manage its own data and share data with other applications on the same device.
4
5> **NOTE**
6>
7> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9> - The APIs of this module can be used only in the stage model.
10
11
12## Modules to Import
13
14```ts
15import { dataShare } from '@kit.ArkData';
16```
17
18
19## dataShare.createDataProxyHandle<sup>20+</sup>
20
21createDataProxyHandle(): Promise&lt;DataProxyHandle&gt;
22
23Creates a **DataProxyHandle** instance. This API uses a promise to return the result.
24
25**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
26
27**Return value**
28
29| Type                                              | Description                                  |
30| -------------------------------------------------- | -------------------------------------- |
31| Promise&lt;[DataProxyHandle](#dataproxyhandle20)&gt; | Promise used to return the result.|
32
33**Error codes**
34
35For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md).
36
37| ID| Error Message                                            |
38| -------- | ---------------------------------------------------- |
39| 15700000 | Inner error. Possible causes: The service is not ready or is being restarted abnormally. |
40
41**Example:**
42```ts
43import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
44import { BusinessError } from '@kit.BasicServicesKit';
45
46export default class EntryAbility extends UIAbility {
47  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
48    dataShare.createDataProxyHandle().then((dataProxyHandle) => {
49      console.info("createDataProxyHandle succeed");
50    }).catch((err: BusinessError) => {
51      console.error(`createDataProxyHandle error: code: ${err.code}, message: ${err.message}`);
52    });
53  };
54};
55```
56
57## ChangeType<sup>20+</sup>
58
59Enumerates the data change types.
60
61**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
62
63| Name    | Value         | Description         |
64| ---------| ------------| --------------|
65| INSERT   | 0           | Data is inserted.|
66| DELETE   | 1           | Data is deleted.|
67| UPDATE   | 2           | Data is updated.|
68
69## ProxyData<sup>20+</sup>
70
71Defines a struct for shared configurations.
72
73**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
74
75| Name      | Type                                                        | Read-Only| Optional| Description          |
76| ---------- | ----------------------------------------------------------- | ----| ---- | -------------- |
77| uri        | string                                                      | No| No | Unique ID of a shared configuration, fixed at the format of **"datashareproxy://{*bundleName*}/{*path*}"**, in which **bundleName** indicates the bundle name of the publisher application, and **path** can be set to any value but must be unique in the same application. The value is a string with a maximum of 255 bytes.|
78| value      | [ValueType](js-apis-data-valuesBucket.md#valuetype)         | No| Yes  | Value of a shared configuration. If not specified, the value is an empty string. The value is a string with a maximum of 4096 bytes. If this parameter is not set when the shared configuration is published for the first time, the value will be an empty string by default. If this parameter is not set when a shared configuration is updated, the value of the shared configuration will not be updated.    |
79| allowList  | string\[]                                         | No| Yes  | List of applications that can subscribe to and read shared configurations. If this parameter is left empty, the value is an empty string array. The array can contain a maximum of 256 elements. Excess elements are invalid. Each element in the array is the **appIdentifier** of an application. The maximum length of a single **appIdentifier** is 128 bytes and the excess value is invalid. If this parameter is not set when the shared configuration is published for the first time, the allowlist is empty by default. If this parameter is not set when the shared configuration is updated, the allowlist will not be updated. An empty allowlist indicates that only the publisher can access the shared configuration. |
80
81## DataProxyChangeInfo<sup>20+</sup>
82
83Defines a struct for notifying subscribers of the shared configuration changes, including data change type, URI, and content.
84
85**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
86
87| Name      | Type                                                        | Read-Only| Optional| Description          |
88| ---------- | ----------------------------------------------------------- | ----| ---- | -------------- |
89| type       | [ChangeType](#changetype20)                                | No| No   | Data change type.|
90| uri       | string                                                        | No| No   | URI to change.|
91| value     | [ValueType](js-apis-data-valuesBucket.md#valuetype)             | No| No    | Changed data.    |
92
93## DataProxyErrorCode<sup>20+</sup>
94
95Enumerates the status code returned by the batch operations of shared configuration.
96
97**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
98
99| Name      | Value                                                         | Description          |
100| ---------- | ----------------------------------------------------------| -------------- |
101| SUCCESS        | 0                                                       | The operation is successful.|
102| URI_NOT_EXIST  | 1                                                       | The URI does not exist or the URI is not subscribed to.|
103| NO_PERMISSION  | 2                                                       | No permission to perform this operation on the URI.|
104| OVER_LIMIT     | 3                                                       | The number of configurations published by the current application exceeds the upper limit of 32. |
105
106## DataProxyResult<sup>20+</sup>
107
108Defines a struct for the batch operation result of shared configuration.
109
110**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
111
112| Name      | Type                                                        | Read-Only| Optional| Description          |
113| ---------- | ----------------------------------------------------------- | ---- | ---- | -------------- |
114| uri        | string                                                      | No| No  | URI to be operated, with a maximum of 256 bytes. The value is fixed at the format of **"datashareproxy://{*bundleName*}/{*path*}"**, in which **bundleName** indicates the bundle name of the publisher application, and **path** can be set to any value but must be unique in the same application.|
115| result  |  [DataProxyErrorCode](#dataproxyerrorcode20)                   | No| No  | Operation result code.|
116
117## DataProxyGetResult<sup>20+</sup>
118
119Defines a struct for obtaining the batch operation result of shared configuration.
120
121**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
122
123| Name      | Type                                                        | Read-Only| Optional| Description          |
124| ---------- | ----------------------------------------------------------- | ---- | ---- | -------------- |
125| uri        | string                                                      | No| No| URI to be operated, with a maximum of 256 bytes. The value is fixed at the format of **"datashareproxy://{*bundleName*}/{*path*}"**, in which **bundleName** indicates the bundle name of the publisher application, and **path** can be set to any value but must be unique in the same application.|
126| result  |  [DataProxyErrorCode](#dataproxyerrorcode20)                   | No| No| Operation result code.|
127| value  |  [ValueType](js-apis-data-valuesBucket.md#valuetype) \| undefined  | No| No| If the operation is successful, the value is the one set in shared configuration; otherwise, the value is undefined.|
128| allowList  |  string\[] \| undefined                             | No| No  | If the operation is successful, the allowlist is the one set in shared configuration; otherwise, the allowlist is undefined. Only the publisher can obtain the allowlist. Other applications can obtain only the value.|
129
130## DataProxyType<sup>20+</sup>
131
132Enumerates the data proxy types.
133
134**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
135
136| Name      | Value                                                        | Description          |
137| ---------- | ---------------------------------------------------------| -------------- |
138| SHARED_CONFIG  | 0                                                   | Inter-application shared configuration.|
139
140## DataProxyConfig<sup>20+</sup>
141
142Defines a struct for the data proxy configuration.
143
144**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
145
146| Name      | Type                                                         | Read-Only| Optional| Description          |
147| ---------- | ----------------------------------------------------------- | ---- | ---- | -------------- |
148| type      | [DataProxyType](#dataproxytype20)                            | No| No  | Type of the data proxy.|
149
150
151## DataProxyHandle<sup>20+</sup>
152
153Defines the data proxy handle, which can be used to access or manage shared configuration information. Before calling an API provided by **DataProxyHandle**, you must create a **DataProxyHandle** instance using [createDataProxyHandle](#datasharecreatedataproxyhandle20).
154
155### on('dataChange')<sup>20+</sup>
156
157on(event: 'dataChange', uris: string[], config: DataProxyConfig, callback: AsyncCallback&lt;DataProxyChangeInfo[]&gt;): DataProxyResult[]
158
159Subscribes to the change event of the shared configuration corresponding to a specified URI. If the change event is subscribed, the subscriber will receive a callback notification that carries the data change type, changed URI, and changed content when the publisher modifies the configuration. This API uses an asynchronous callback to return the result. This function does not support cross-user notification subscription or subscription to unpublished configurations. If the permission is revoked after the subscription is successful, the subscriber will not be notified consequently.
160
161When the configuration publisher calls the [publish](#publish20) or [delete](#delete20) API to publish or delete a configuration, a notification is automatically triggered.
162
163**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
164
165**Parameters**
166
167| Name    | Type                       | Mandatory| Description                   |
168| -------- | ----------------------------- | ---- | ------------------------ |
169| event     | string                        | Yes  | Event or callback type. The value is **dataChange**, which indicates the data change. This event is triggered when the configuration publisher modifies the configuration.|
170| uris     | string\[]             | Yes  | Array of URIs to be subscribed, with a maximum of 32 URIs. The value is fixed at the format of **"datashareproxy://{*bundleName*}/{*path*}"**, in which **bundleName** indicates the bundle name of the publisher application, and **path** can be set to any value but must be unique in the same application.|
171| config      | [DataProxyConfig](#dataproxyconfig20)               | Yes  | Data proxy configuration.|
172| callback | AsyncCallback&lt;[DataProxyChangeInfo](#dataproxychangeinfo20)\[]&gt; | Yes  | Callback triggered when the publisher modifies the configuration.|
173
174**Return value**
175
176| Type            | Description                                                        |
177| ---------------- | ------------------------------------------------------------ |
178| [DataProxyResult](#dataproxyresult20)\[] | Batch operation result array.|
179
180**Error codes**
181
182For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md).
183
184| ID| Error Message             |
185| -------- | -------------------- |
186| 15700000 | Inner error. Possible causes: The service is not ready or is being restarted abnormally.|
187| 15700014 | The parameter format is incorrect or the value range is invalid.|
188
189**Example:**
190
191```ts
192const urisToWatch: string[] =
193  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
194const config: dataShare.DataProxyConfig = {
195  type: dataShare.DataProxyType.SHARED_CONFIG,
196};
197const callback = (err: BusinessError<void>, changes: dataShare.DataProxyChangeInfo[]): void => {
198  if (err) {
199    console.error('err:', err);
200  } else {
201    changes.forEach((change) => {
202      console.info(`Change Type: ${change.type}, URI: ${change.uri}, Value: ${change.value}`);
203    });
204  }
205};
206const results: dataShare.DataProxyResult[] = dataProxyHandle.on('dataChange', urisToWatch, config, callback);
207results.forEach((result) => {
208  console.info(`URI: ${result.uri}, Result: ${result.result}`);
209});
210```
211
212### off('dataChange')<sup>20+</sup>
213
214off(event: 'dataChange', uris: string[], config: DataProxyConfig, callback?: AsyncCallback&lt;DataProxyChangeInfo[]&gt;): DataProxyResult[]
215
216Unsubscribes from the change event of the proxy data corresponding to a specified URI.
217
218**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
219
220**Parameters**
221
222| Name    | Type                       | Mandatory| Description                   |
223| -------- | ----------------------------- | ---- | ------------------------ |
224| event     | string                        | Yes  | Event or callback type. The value is **dataChange**, which indicates the data change.|
225| uris     | string\[]             | Yes  | Array of URIs to be unsubscribed, with a maximum of 32 URIs. The value is fixed at the format of **"datashareproxy://{*bundleName*}/{*path*}"**, in which **bundleName** indicates the bundle name of the publisher application, and **path** can be set to any value but must be unique in the same application.|
226| config      | [DataProxyConfig](#dataproxyconfig20)               | Yes  | Data proxy configuration.|
227| callback | AsyncCallback&lt;[DataProxyChangeInfo](#dataproxychangeinfo20)\[]&gt; | No  | Callback to unregister. If the value is empty, undefined, or null, all notifications of the URIs are unsubscribed.|
228
229**Return value**
230
231| Type            | Description                                                        |
232| ---------------- | ------------------------------------------------------------ |
233| [DataProxyResult](#dataproxyresult20)\[] | Batch operation result array.|
234
235**Error codes**
236
237For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md).
238
239| ID| Error Message             |
240| -------- | -------------------- |
241| 15700000 | Inner error. Possible causes: The service is not ready or is being restarted abnormally.|
242| 15700014 | The parameter format is incorrect or the value range is invalid.|
243
244**Example:**
245
246```ts
247const urisToUnWatch: string[] =
248  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
249const config: dataShare.DataProxyConfig = {
250  type: dataShare.DataProxyType.SHARED_CONFIG,
251};
252const callback = (err: BusinessError<void>, changes: dataShare.DataProxyChangeInfo[]): void => {
253  if (err) {
254    console.error('err:', err);
255  } else {
256    changes.forEach((change) => {
257      console.info(`Change Type: ${change.type}, URI: ${change.uri}, Value: ${change.value}`);
258    });
259  }
260};
261const results: dataShare.DataProxyResult[] = dataProxyHandle.off('dataChange', urisToUnWatch, config, callback);
262results.forEach((result) => {
263  console.info(`URI: ${result.uri}, Result: ${result.result}`);
264});
265```
266
267### publish<sup>20+</sup>
268
269publish(data: ProxyData[], config: DataProxyConfig): Promise&lt;DataProxyResult[]&gt;
270
271Publishes shared configuration items. After the publish, the publisher and the applications in the allowlist can access these items. If the URI to be published already exists, the corresponding shared configuration item is updated. If any URI in the configuration item to be published exceeds the maximum length or fails the format verification, the current publish operation fails. Only the publisher can update shared configuration items. Each application supports a maximum of 32 shared configurations.
272
273**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
274
275**Parameters**
276
277| Name    | Type                       | Mandatory| Description                   |
278| -------- | ----------------------------- | ---- | ------------------------ |
279| data     | [ProxyData](#proxydata20)\[]       | Yes  | Array of shared configuration items to be created or updated, with a maximum of 32 items.|
280| config   | [DataProxyConfig](#dataproxyconfig20)   | Yes  | Data proxy configuration.|
281
282**Return value**
283
284| Type            | Description                                                        |
285| ---------------- | ------------------------------------------------------------ |
286| Promise&lt;[DataProxyResult](#dataproxyresult20)\[]&gt; | Promise used to return the result array of the batch operations.|
287
288**Error codes**
289
290For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md).
291
292| ID| Error Message             |
293| -------- | -------------------- |
294| 15700000 | Inner error. Possible causes: The service is not ready or is being restarted abnormally.|
295| 15700014 | The parameter format is incorrect or the value range is invalid.|
296
297**Example:**
298
299```ts
300const newConfigData: dataShare.ProxyData[] = [{
301  uri: 'datashareproxy://com.example.app1/config1',
302  value: 'Value1',
303  allowList: ['com.example.app2', 'com.example.app3'],
304}, {
305  uri: 'datashareproxy://com.example.app1/config2',
306  value: 'Value2',
307  allowList: ['com.example.app3', 'com.example.app4'],
308},];
309const config: dataShare.DataProxyConfig = {
310  type: dataShare.DataProxyType.SHARED_CONFIG,
311};
312dataProxyHandle.publish(newConfigData, config).then((results: dataShare.DataProxyResult[]) => {
313  results.forEach((result) => {
314    console.info(`URI: ${result.uri}, Result: ${result.result}`);
315  });
316}).catch((error: BusinessError) => {
317  console.error('Error publishing config:', error);
318});
319```
320
321### delete<sup>20+</sup>
322
323delete(uris: string[], config: DataProxyConfig): Promise&lt;DataProxyResult[]&gt;
324
325Deletes the specified shared configuration items based on the URI. Only the publisher can delete the shared configuration items.
326
327**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
328
329**Parameters**
330
331| Name    | Type                       | Mandatory| Description                   |
332| -------- | ----------------------------- | ---- | ------------------------ |
333| uris     | string\[]          | Yes  | URI array of the shared configuration items to be deleted, with a maximum of 32 URIs. The value is fixed at the format of **"datashareproxy://{*bundleName*}/{*path*}"**, in which **bundleName** indicates the bundle name of the publisher application, and **path** can be set to any value but must be unique in the same application.|
334| config   | [DataProxyConfig](#dataproxyconfig20)   | Yes  | Shared configuration type.|
335
336**Return value**
337
338| Type            | Description                                                        |
339| ---------------- | ------------------------------------------------------------ |
340| Promise&lt;[DataProxyResult](#dataproxyresult20)\[]&gt; | Promise used to return the result array of the batch operations.|
341
342**Error codes**
343
344For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md).
345
346| ID| Error Message             |
347| -------- | -------------------- |
348| 15700000 | Inner error. Possible causes: The service is not ready or is being restarted abnormally.|
349| 15700014 | The parameter format is incorrect or the value range is invalid.|
350
351**Example:**
352
353```ts
354const urisToDelete: string[] =
355  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
356const config: dataShare.DataProxyConfig = {
357  type: dataShare.DataProxyType.SHARED_CONFIG,
358};
359dataProxyHandle.delete(urisToDelete, config).then((results: dataShare.DataProxyResult[]) => {
360  results.forEach((result) => {
361    console.info(`URI: ${result.uri}, Result: ${result.result}`);
362  });
363}).catch((error: BusinessError) => {
364  console.error('Error deleting config:', error);
365});
366```
367
368### get<sup>20+</sup>
369
370get(uris: string[], config: DataProxyConfig): Promise&lt;DataProxyGetResult[]&gt;
371
372Obtains a specified shared configuration item based on the URI. Only the publisher and applications in the allowed list can access the shared configuration item.
373
374**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
375
376**Parameters**
377
378| Name    | Type                       | Mandatory| Description                   |
379| -------- | ----------------------------- | ---- | ------------------------ |
380| uris     | string\[]         | Yes  | URI array of the shared configuration items to be obtained, with a maximum of 32 URIs. The value is fixed at the format of **"datashareproxy://{*bundleName*}/{*path*}"**, in which **bundleName** indicates the bundle name of the publisher application, and **path** can be set to any value but must be unique in the same application.|
381| config   | [DataProxyConfig](#dataproxyconfig20)   | Yes  | Shared configuration type.|
382
383**Return value**
384
385| Type            | Description                                                        |
386| ---------------- | ------------------------------------------------------------ |
387| Promise&lt;[DataProxyGetResult](#dataproxygetresult20)\[]&gt; | Promise used to return the result array of the batch operations.|
388
389**Error codes**
390
391For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md).
392
393| ID| Error Message             |
394| -------- | -------------------- |
395| 15700000 | Inner error. Possible causes: The service is not ready or is being restarted abnormally.|
396| 15700014 | The parameter format is incorrect or the value range is invalid.|
397
398**Example:**
399
400```ts
401const urisToGet: string[] =
402  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
403const config: dataShare.DataProxyConfig = {
404  type: dataShare.DataProxyType.SHARED_CONFIG,
405};
406dataProxyHandle.get(urisToGet, config).then((results: dataShare.DataProxyGetResult[]) => {
407  results.forEach((result) => {
408    console.info(`URI: ${result.uri}, Result: ${result.result}, AllowList: ${result.allowList}`);
409  });
410}).catch((error: BusinessError) => {
411  console.error('Error getting config:', error);
412});
413```
414