• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Sharing Data via Unified Data Channels (ArkTS)
2
3
4## When to Use
5
6In many-to-many data sharing across applications, a data channel needs to be provided to access data of different applications and share the data with other applications.
7
8The Unified Data Management Framework (UDMF) provides unified data channels and standard data access interfaces for different service scenarios of many-to-many cross-application data sharing.
9
10## Definition and Implementation of Unified Data Channels
11
12The unified data channel provides cross-application data access for various service scenarios. It can temporarily store the unified data objects to be shared by an application, and manage the data modification and deletion permissions and lifecycle of the data according to certain policies.
13
14The unified data channel is implemented by the system ability provided by the UDMF. When an application (data provider) needs to share data, it calls the **insertData()** method provided by the UDMF to write the data to the UDMF data channel, and calls UDMF **updateData()** or **deleteData()** to update or delete the data saved by the application. The target application (data consumer) can access the data by the APIs provided by the UDMF. The UDMF manages the data lifecycle in a unified manner and deletes the data that has been stored for more than one hour every hour.
15
16Avoid using **unifiedDataChannel** APIs in multi-threaded calls.
17
18The unified data object (**UnifiedData**) is uniquely identified by a URI in the UDMF data channel. The URI is in the **udmf://*intention*/*bundleName*/*groupId*** format, where:
19
20+ **udmf**: protocol used to provide the data channel.
21
22+ *intention*: an enum of the data channel types supported by the UDMF.
23
24+ *bundleName*: bundle name of the data source application.
25
26+ *groupId*: group ID used for batch data management.
27
28Currently, the UDMF provides the public data channel for cross-application data sharing.
29
30The public data channel allows all applications to write data into it. When data is written, a unique identifier is generated. Then, the unique identifier can be used to update, delete, query, and retrieve the specified data, and perform a full query. To read all data in the public data channel, set **Intention** to **DATA_HUB**. The public data channel is used only to transmit process data between applications and cannot be used to transmit permission-controlled data, such as files in sandbox directories.
31
32## Available APIs
33
34The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For details about more APIs and their usage, see [Unified Data Channel](../reference/apis-arkdata/js-apis-data-unifiedDataChannel.md) and [Standard Data Definition and Description](../reference/apis-arkdata/js-apis-data-uniformTypeDescriptor.md).
35
36| API                                                                                   | Description                                         |
37|-----------------------------------------------------------------------------------------|---------------------------------------------|
38| insertData(options: Options, data: UnifiedData, callback: AsyncCallback\<string>): void | Inserts data to the UDMF public data channel. A unique data identifier is returned.|
39| updateData(options: Options, data: UnifiedData, callback: AsyncCallback\<void>): void   | Updates the data in the UDMF public data channel.          |
40| queryData(options: Options, callback: AsyncCallback\<Array\<UnifiedData>>): void        | Queries data in the UDMF public data channel.              |
41| deleteData(options: Options, callback: AsyncCallback\<Array\<UnifiedData>>): void       | Deletes data from the UDMF public data channel. The deleted data set is returned.|
42
43
44## How to Develop
45
46The following example walks you through on how to implement many-to-many sharing of PlainText, HTML, and PixelMap data. The data provider calls **insertData()** provided by the UMDF to write data to the public data channel. The return value (unique identifier of the data written) can be used to update or delete the data. The data consumer uses the query() APIs provided by the UDMF to obtain full data of the public data channel.
47
48### Data Provider
49
501. Import the **unifiedDataChannel**, **uniformTypeDescriptor**, and **uniformDataStruct** modules.
51
52   ```ts
53   import { unifiedDataChannel, uniformTypeDescriptor, uniformDataStruct } from '@kit.ArkData';
54   ```
552. Create a **UnifiedData** object and insert it into the UDMF public data channel.
56
57   ```ts
58   import { BusinessError } from '@kit.BasicServicesKit';
59   import { image } from '@kit.ImageKit';
60   // Create plaintext data.
61   let plainTextObj : uniformDataStruct.PlainText = {
62     uniformDataType: 'general.plain-text',
63     textContent : 'Hello world',
64     abstract : 'This is abstract',
65   }
66   let record = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, plainTextObj);
67   // Create HTML data.
68   let htmlObj : uniformDataStruct.HTML = {
69     uniformDataType :'general.html',
70     htmlContent : '<div><p>Hello world</p></div>',
71     plainContent : 'Hello world',
72   }
73   // Add a new entry to the data record, storing the same data in another format.
74   record.addEntry(uniformTypeDescriptor.UniformDataType.HTML, htmlObj);
75   let unifiedData = new unifiedDataChannel.UnifiedData(record);
76
77   // Create pixelMap data.
78   let arrayBuffer = new ArrayBuffer(4*3*3);
79   let opt : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 3, width: 3 }, alphaType: 3 };
80   let pixelMap : uniformDataStruct.PixelMap = {
81     uniformDataType : 'openharmony.pixel-map',
82     pixelMap : image.createPixelMapSync(arrayBuffer, opt),
83   }
84   unifiedData.addRecord(new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.OPENHARMONY_PIXEL_MAP, pixelMap));
85   // Specify the type of the data channel to which the data is to be inserted.
86   let options: unifiedDataChannel.Options = {
87     intention: unifiedDataChannel.Intention.DATA_HUB
88   }
89   try {
90     unifiedDataChannel.insertData(options, unifiedData, (err, key) => {
91       if (err === undefined) {
92         console.info(`Succeeded in inserting data. key = ${key}`);
93       } else {
94         console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
95       }
96     });
97   } catch (e) {
98     let error: BusinessError = e as BusinessError;
99     console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
100   }
101   ```
1023. Update the **UnifiedData** object inserted.
103
104   ```ts
105   let plainTextUpdate : uniformDataStruct.PlainText = {
106     uniformDataType: 'general.plain-text',
107     textContent : 'How are you',
108     abstract : 'This is abstract',
109   }
110   let recordUpdate = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, plainTextUpdate);
111   let htmlUpdate : uniformDataStruct.HTML = {
112     uniformDataType :'general.html',
113     htmlContent : '<div><p>How are you</p></div>',
114     plainContent : 'How are you',
115   }
116   recordUpdate.addEntry(uniformTypeDescriptor.UniformDataType.HTML, htmlUpdate);
117   let unifiedDataUpdate = new unifiedDataChannel.UnifiedData(recordUpdate);
118
119   // Specify the URI of the UnifiedData object to update.
120   let optionsUpdate: unifiedDataChannel.Options = {
121     //The key here is an example and cannot be directly used. Use the value in the callback of insertData().
122     key: 'udmf://DataHub/com.ohos.test/0123456789'
123   };
124
125   try {
126     unifiedDataChannel.updateData(optionsUpdate, unifiedDataUpdate, (err) => {
127       if (err === undefined) {
128         console.info('Succeeded in updating data.');
129       } else {
130         console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
131       }
132     });
133   } catch (e) {
134     let error: BusinessError = e as BusinessError;
135     console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `);
136   }
137   ```
1384. Delete the **UnifiedData** object from the UDMF public data channel.
139
140   ```ts
141   // Specify the type of the data channel whose data is to be deleted.
142   let optionsDelete: unifiedDataChannel.Options = {
143     intention: unifiedDataChannel.Intention.DATA_HUB
144   };
145
146   try {
147     unifiedDataChannel.deleteData(optionsDelete, (err, data) => {
148       if (err === undefined) {
149         console.info(`Succeeded in deleting data. size = ${data.length}`);
150         for (let i = 0; i < data.length; i++) {
151           let records = data[i].getRecords();
152           for (let j = 0; j < records.length; j++) {
153             let types = records[j].getTypes();
154             // Obtain data of the specified format from the record based on service requirements.
155             if (types.includes(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT)) {
156               let text = records[j].getEntry(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) as uniformDataStruct.PlainText;
157               console.info(`${i + 1}.${text.textContent}`);
158             }
159             if (types.includes(uniformTypeDescriptor.UniformDataType.HTML)) {
160               let html = records[j].getEntry(uniformTypeDescriptor.UniformDataType.HTML) as uniformDataStruct.HTML;
161               console.info(`${i + 1}.${html.htmlContent}`);
162             }
163           }
164         }
165       } else {
166         console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
167       }
168     });
169   } catch (e) {
170     let error: BusinessError = e as BusinessError;
171     console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `);
172   }
173   ```
174
175### Data Consumer
176
1771. Import the **unifiedDataChannel**, **uniformTypeDescriptor**, and **uniformDataStruct** modules.
178
179   ```ts
180   import { unifiedDataChannel, uniformTypeDescriptor, uniformDataStruct } from '@kit.ArkData';
181   ```
1822. Query the full data in the UDMF public data channel.
183
184   ```ts
185   import { BusinessError } from '@kit.BasicServicesKit';
186   // Specify the type of the data channel whose data is to be queried.
187   let options: unifiedDataChannel.Options = {
188     intention: unifiedDataChannel.Intention.DATA_HUB
189   };
190
191   try {
192     unifiedDataChannel.queryData(options, (err, data) => {
193       if (err === undefined) {
194         console.info(`Succeeded in querying data. size = ${data.length}`);
195         for (let i = 0; i < data.length; i++) {
196           let records = data[i].getRecords();
197           for (let j = 0; j < records.length; j++) {
198             let types = records[j].getTypes();
199             // Obtain data of the specified format from the record based on service requirements.
200             if (types.includes(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT)) {
201               let text = records[j].getEntry(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) as uniformDataStruct.PlainText;
202               console.info(`${i + 1}.${text.textContent}`);
203             }
204             if (types.includes(uniformTypeDescriptor.UniformDataType.HTML)) {
205               let html = records[j].getEntry(uniformTypeDescriptor.UniformDataType.HTML) as uniformDataStruct.HTML;
206               console.info(`${i + 1}.${html.htmlContent}`);
207             }
208           }
209         }
210       } else {
211         console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
212       }
213     });
214   } catch(e) {
215     let error: BusinessError = e as BusinessError;
216     console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
217   }
218   ```
219