未验证 提交 7e9154af 编写于 作者: O openharmony_ci 提交者: Gitee

!15234 [翻译完成】#I6DYG9

Merge pull request !15234 from Annie_wang/PR14435
...@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share ...@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share
|query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.| |query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.| |delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.|
For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md).
**Table 2** APIs of the data consumer **Table 2** APIs of the data consumer
...@@ -34,11 +34,49 @@ There are two roles in **DataShare**: ...@@ -34,11 +34,49 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### Data Provider Application Development (Only for System Applications) ### Data Provider Application Development (Only for System Applications)
1. Import dependencies. [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
- **onCreate**
Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server.
- **insert**
Inserts data. This API is called when the client requests to insert data.
- **update**
Updates data. This API is called when the client requests to update data.
- **delete**
Deletes data. This API is called when the client requests to delete data.
- **query**
Queries data. This API is called when the client requests to query data.
- **batchInsert**
Batch inserts data. This API is called when the client requests to batch insert data.
- **normalizeUri**
Converts the URI provided by the client to the URI used by the server.
- **denormalizeUri**
Converts the URI used by the server to the initial URI passed by the client.
Before implementing a **DataShare** service, you need to create a **DataShareExtensionAbility** object in the DevEco Studio project as follows:
1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **DataShareAbility**.
2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**.
3. In the **DataShareAbility.ts** file, import **DataShareExtensionAbility** and other dependencies.
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
...@@ -47,9 +85,9 @@ Examples are given below. ...@@ -47,9 +85,9 @@ Examples are given below.
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. 4. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. 5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts ```ts
const DB_NAME = "DB00.db"; const DB_NAME = "DB00.db";
...@@ -63,20 +101,22 @@ Examples are given below. ...@@ -63,20 +101,22 @@ Examples are given below.
export default class DataShareExtAbility extends Extension { export default class DataShareExtAbility extends Extension {
private rdbStore_; private rdbStore_;
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt' result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store. // Create an RDB store.
rdb.getRdbStore(this.context, { rdb.getRdbStore(this.context, {
name: DB_NAME, name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1 securityLevel: rdb.SecurityLevel.S1
}, function (err, data) { }, function (err, data) {
rdbStore = data; rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
}); });
callback(); if (callback) {
callback();
}
}); });
} }
...@@ -103,19 +143,20 @@ Examples are given below. ...@@ -103,19 +143,20 @@ Examples are given below.
}; };
``` ```
4. Define **DataShareExtensionAbility** in **module.json5**.
| Field| Description | 6. Define **DataShareExtensionAbility** in **module.json5**.
| ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
**module.json5 example** | Field | Description |
| --------- | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. |
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. |
**module.json5 example**
```json ```json
"extensionAbilities": [ "extensionAbilities": [
{ {
"srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts", "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts",
"name": "DataShareExtAbility", "name": "DataShareExtAbility",
...@@ -127,31 +168,33 @@ Examples are given below. ...@@ -127,31 +168,33 @@ Examples are given below.
} }
] ]
``` ```
### Data Consumer Application Development ### Data Consumer Application Development
1. Import dependencies. 1. Import dependencies.
```ts ```ts
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
import dataShare from '@ohos.data.dataShare'; import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
2. Define the URI string for communicating with the data provider. 2. Define the URI string for communicating with the data provider.
```ts ```ts
// Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); let dseUri = ("datashare:///com.samples.datasharetest.DataShare");
``` ```
3. Create a **DataShareHelper** instance. 3. Create a **DataShareHelper** instance.
```ts ```ts
let dsHelper; let dsHelper;
let abilityContext; let abilityContext;
export default class MainAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
abilityContext = this.context; abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{ dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
...@@ -160,7 +203,7 @@ Examples are given below. ...@@ -160,7 +203,7 @@ Examples are given below.
} }
} }
``` ```
4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. 4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data.
```ts ```ts
...@@ -168,7 +211,7 @@ Examples are given below. ...@@ -168,7 +211,7 @@ Examples are given below.
let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*"); let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log("dsHelper insert result: " + data);
...@@ -183,7 +226,6 @@ Examples are given below. ...@@ -183,7 +226,6 @@ Examples are given below.
}); });
// Delete data. // Delete data.
dsHelper.delete(dseUri, predicates, (err, data) => { dsHelper.delete(dseUri, predicates, (err, data) => {
console.log("dsHelper delete result: " + data); console.log("dsHelper delete result: " + data);
}); });
``` ```
...@@ -14,12 +14,12 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis ...@@ -14,12 +14,12 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management. | | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management. |
| getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.| | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. | | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. | | delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. | | get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Obtains data. |
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): void | Subscribes to data changes in the KV store. | | on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): void | Subscribes to data changes in the KV store. |
| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | | sync(deviceIdList: string[], mode: SyncMode, delayMs?: number): void | Triggers database synchronization in manual mode. |
## How to Develop ## How to Develop
...@@ -61,32 +61,32 @@ The following uses a single KV store as an example to describe the development p ...@@ -61,32 +61,32 @@ The following uses a single KV store as an example to describe the development p
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => {
console.info('success: ${data}'); console.info('success: ${data}');
}).catch((error) => { }).catch((error) => {
console.info('failed: ${error}'); console.error('failed: ${error}');
}) })
} }
grantPermission(); grantPermission();
// Stage model // Stage model
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
function grantPermission() { class EntryAbility extends UIAbility {
class MainAbility extends Ability { onWindowStageCreate(windowStage) {
onWindowStageCreate(windowStage) {
let context = this.context; let context = this.context;
} }
} }
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; function grantPermission() {
context.requestPermissionsFromUser(permissions).then((data) => { let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success: ${data}'); console.log('success: ${data}');
}).catch((error) => { }).catch((error) => {
console.log('failed: ${error}'); console.error('failed: ${error}');
}); });
} }
grantPermission(); grantPermission();
``` ```
...@@ -103,9 +103,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -103,9 +103,9 @@ The following uses a single KV store as an example to describe the development p
let context = featureAbility.getContext(); let context = featureAbility.getContext();
// Obtain the context of the stage model. // Obtain the context of the stage model.
import AbilityStage from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends AbilityStage{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -119,7 +119,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -119,7 +119,7 @@ The following uses a single KV store as an example to describe the development p
} }
distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) {
if (err) { if (err) {
console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Created KVManager successfully'); console.log('Created KVManager successfully');
......
...@@ -113,10 +113,10 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -113,10 +113,10 @@ You can use the following APIs to delete a **Preferences** instance or data file
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability' import UIAbility from '@ohos.app.ability.UIAbility'
let context = null; let context = null;
let preferences = null; let preferences = null;
export default class MainAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -159,7 +159,7 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -159,7 +159,7 @@ You can use the following APIs to delete a **Preferences** instance or data file
5. Store data persistently. 5. Store data persistently.
Use **flush()** to flush data from the **Preferences** instance to its file. Use **preferences.flush()** to flush data from the **Preferences** instance to its file.
```js ```js
preferences.flush(); preferences.flush();
...@@ -186,7 +186,7 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -186,7 +186,7 @@ You can use the following APIs to delete a **Preferences** instance or data file
console.info("Failed to flush data. Cause: " + err); console.info("Failed to flush data. Cause: " + err);
return; return;
} }
console.info("Flushed data successfully."); // The observer will be called. console.info("Flushed data successfully."); // The observer will be called.
}) })
}) })
``` ```
...@@ -200,6 +200,6 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -200,6 +200,6 @@ You can use the following APIs to delete a **Preferences** instance or data file
proDelete.then(() => { proDelete.then(() => {
console.info("Deleted data successfully."); console.info("Deleted data successfully.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to delete data. Cause: " + err); console.info("Failed to delete data. Cause: " + err);
}) })
``` ```
# @ohos.data.dataShare (DataShare) # @ohos.data.dataShare (Data Sharing)
The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. The **DataShare** module allows an application to manage its own data and share data with other applications on the same device.
...@@ -37,18 +37,12 @@ Example: ...@@ -37,18 +37,12 @@ Example:
**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. **com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path.
## dataShare.createDataShareHelper ## dataShare.createDataShareHelper
createDataShareHelper(context: Context, uri: string, callback: AsyncCallback&lt;DataShareHelper&gt;): void createDataShareHelper(context: Context, uri: string, callback: AsyncCallback&lt;DataShareHelper&gt;): void
Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -70,7 +64,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err ...@@ -70,7 +64,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let dataShareHelper; let dataShareHelper;
...@@ -94,11 +88,6 @@ createDataShareHelper(context: Context, uri: string): Promise&lt;DataShareHelper ...@@ -94,11 +88,6 @@ createDataShareHelper(context: Context, uri: string): Promise&lt;DataShareHelper
Creates a **DataShareHelper** instance. This API uses a promise to return the result. Creates a **DataShareHelper** instance. This API uses a promise to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -125,7 +114,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err ...@@ -125,7 +114,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let dataShareHelper; let dataShareHelper;
...@@ -164,8 +153,7 @@ Subscribes to changes of the specified data. After an observer is registered, th ...@@ -164,8 +153,7 @@ Subscribes to changes of the specified data. After an observer is registered, th
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
function onCallback() { function onCallback() {
console.info("**** Observer on callback ****"); console.info("**** Observer on callback ****");
} }
...@@ -187,13 +175,12 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono ...@@ -187,13 +175,12 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono
| -------- | -------------------- | ---- | ------------------------ | | -------- | -------------------- | ---- | ------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| | type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.|
| uri | string | Yes | URI of the data.| | uri | string | Yes | URI of the data.|
| callback | AsyncCallback&lt;void&gt; | No | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | No | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
function offCallback() { function offCallback() {
console.info("**** Observer off callback ****"); console.info("**** Observer off callback ****");
} }
...@@ -220,8 +207,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca ...@@ -220,8 +207,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
const valueBucket = { const valueBucket = {
"name": "rose", "name": "rose",
...@@ -265,8 +251,7 @@ Inserts a single data record into the database. This API uses a promise to retur ...@@ -265,8 +251,7 @@ Inserts a single data record into the database. This API uses a promise to retur
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
const valueBucket = { const valueBucket = {
"name": "rose1", "name": "rose1",
...@@ -303,8 +288,8 @@ Deletes one or more data records from the database. This API uses an asynchronou ...@@ -303,8 +288,8 @@ Deletes one or more data records from the database. This API uses an asynchronou
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates(); let da = new dataSharePredicates.DataSharePredicates();
...@@ -346,8 +331,8 @@ Deletes one or more data records from the database. This API uses a promise to r ...@@ -346,8 +331,8 @@ Deletes one or more data records from the database. This API uses a promise to r
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates(); let da = new dataSharePredicates.DataSharePredicates();
...@@ -383,8 +368,8 @@ Queries data in the database. This API uses an asynchronous callback to return t ...@@ -383,8 +368,8 @@ Queries data in the database. This API uses an asynchronous callback to return t
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let columns = ["*"]; let columns = ["*"];
...@@ -428,8 +413,8 @@ Queries data in the database. This API uses a promise to return the result. ...@@ -428,8 +413,8 @@ Queries data in the database. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let columns = ["*"]; let columns = ["*"];
...@@ -466,8 +451,8 @@ Updates data in the database. This API uses an asynchronous callback to return t ...@@ -466,8 +451,8 @@ Updates data in the database. This API uses an asynchronous callback to return t
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates(); let da = new dataSharePredicates.DataSharePredicates();
...@@ -516,8 +501,8 @@ Updates data in the database. This API uses a promise to return the result. ...@@ -516,8 +501,8 @@ Updates data in the database. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates(); let da = new dataSharePredicates.DataSharePredicates();
...@@ -558,8 +543,7 @@ Batch inserts data into the database. This API uses an asynchronous callback to ...@@ -558,8 +543,7 @@ Batch inserts data into the database. This API uses an asynchronous callback to
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,},
{"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,},
...@@ -601,8 +585,7 @@ Batch inserts data into the database. This API uses a promise to return the resu ...@@ -601,8 +585,7 @@ Batch inserts data into the database. This API uses a promise to return the resu
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,},
{"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,},
...@@ -636,8 +619,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo ...@@ -636,8 +619,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.normalizeUri(uri, (err, data) => { dataShareHelper.normalizeUri(uri, (err, data) => {
if (err != undefined) { if (err != undefined) {
...@@ -671,8 +653,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo ...@@ -671,8 +653,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.normalizeUri(uri).then((data) => { dataShareHelper.normalizeUri(uri).then((data) => {
console.log("normalizeUri = " + data); console.log("normalizeUri = " + data);
...@@ -699,8 +680,7 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result. ...@@ -699,8 +680,7 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result.
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.denormalizeUri(uri, (err, data) => { dataShareHelper.denormalizeUri(uri, (err, data) => {
if (err != undefined) { if (err != undefined) {
...@@ -734,8 +714,7 @@ Denormalizes a URI. This API uses a promise to return the result. ...@@ -734,8 +714,7 @@ Denormalizes a URI. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.denormalizeUri(uri).then((data) => { dataShareHelper.denormalizeUri(uri).then((data) => {
console.log("denormalizeUri = " + data); console.log("denormalizeUri = " + data);
...@@ -762,8 +741,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous ...@@ -762,8 +741,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.notifyChange(uri, () => { dataShareHelper.notifyChange(uri, () => {
console.log("***** notifyChange *****"); console.log("***** notifyChange *****");
...@@ -793,8 +771,7 @@ Notifies the registered observer of data changes. This API uses a promise to ret ...@@ -793,8 +771,7 @@ Notifies the registered observer of data changes. This API uses a promise to ret
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.notifyChange(uri); dataShareHelper.notifyChange(uri);
``` ```
...@@ -13,32 +13,57 @@ The **distributedDataObject** module provides basic data object management, incl ...@@ -13,32 +13,57 @@ The **distributedDataObject** module provides basic data object management, incl
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
``` ```
## distributedDataObject.createDistributedObject ## distributedObject.create<sup>9+</sup>
createDistributedObject(source: object): DistributedObject
create(context: Context, source: object): DistributedObjectV9
Creates a distributed data object. Creates a distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.| | context | Context | Yes| Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md).|
| source | object | Yes| Attributes of the distributed data object.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [DistributedObject](#distributedobject) | Distributed data object created.| | [DistributedObjectV9](#distributedobjectv9) | Distributed data object created.|
**Example** **Example**
FA model:
```js ```js
// Import the module.
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. import featureAbility from '@ohos.ability.featureAbility';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // Obtain the context.
let context = featureAbility.getContext();
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
``` ```
Stage model:
```ts
// Import the module.
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
```
## distributedObject.genSessionId ## distributedObject.genSessionId
...@@ -49,14 +74,16 @@ Creates a random session ID. ...@@ -49,14 +74,16 @@ Creates a random session ID.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| string | Session ID created.| | string | Session ID created.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var sessionId = distributedObject.genSessionId(); let sessionId = distributedObject.genSessionId();
``` ```
## SaveSuccessResponse<sup>9+</sup> ## SaveSuccessResponse<sup>9+</sup>
...@@ -65,11 +92,11 @@ Called when the **Save()** API is successfully called. ...@@ -65,11 +92,11 @@ Called when the **Save()** API is successfully called.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
| Name| Type| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sessionId | string | Unique ID for multi-device collaboration.| | sessionId | string | Yes| Unique ID for multi-device collaboration.|
| version | number |Version of the distributed data object saved.| | version | number | Yes| Version of the distributed data object saved.|
| deviceId | string | ID of the device where the distributed data object is stored. The default value is **local**, which identifies a local device. You can set it as required.| | deviceId | string | Yes| ID of the device where the distributed data object is stored. The default value is **local**, which identifies a local device. You can set it as required.|
## RevokeSaveSuccessResponse<sup>9+</sup> ## RevokeSaveSuccessResponse<sup>9+</sup>
...@@ -77,17 +104,142 @@ Called when the **revokeSave()** API is successfully called. ...@@ -77,17 +104,142 @@ Called when the **revokeSave()** API is successfully called.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
| Name| Type| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sessionId | string | Unique ID for multi-device collaboration.| | sessionId | string | Yes| Unique ID for multi-device collaboration.|
## DistributedObject ## DistributedObjectV9
Represents a distributed data object. Represents a distributed data object.
### setSessionId ### setSessionId<sup>9+</sup>
setSessionId(sessionId?: string): boolean setSessionId(sessionId: string, callback: AsyncCallback&lt;void&gt;): void
Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | Yes| ID of a distributed data object on a trusted network.|
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the session ID is successfully set.|
**Error codes**
For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
| 15400001 | Failed to create the in-memory database.|
**Example**
FA model:
```js
import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId(), ()=>{
console.log("join session");
});
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId(), ()=>{
console.log("join session");
});
```
### setSessionId<sup>9+</sup>
setSessionId(callback: AsyncCallback&lt;void&gt;): void
Exits all joined sessions.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.|
**Error codes**
For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
| 15400001 | Failed to create the in-memory database.|
**Example**
FA model:
```js
import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId(), ()=>{
console.log("join session");
});
// Exit the distributed network.
g_object.setSessionId(() => {
console.log("leave all lession.");
});
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId(), ()=>{
console.log("join session");
});
// Exit the distributed network.
g_object.setSessionId(() => {
console.log("leave all lession.");
});
```
### setSessionId<sup>9+</sup>
setSessionId(sessionId?: string): Promise&lt;void&gt;
Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network.
...@@ -105,38 +257,115 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -105,38 +257,115 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. | | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
| 15400001 | Failed to create the in-memory database.|
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network. // Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId()); g_object.setSessionId(distributedObject.genSessionId()).then (()=>{
// Remove g_object from the distributed network. console.log("join session.");
g_object.setSessionId(""); }).catch((error)=>{
console.info("error:" + error.code + error.message);
});
// Exit the distributed network.
g_object.setSessionId().then (()=>{
console.log("leave all lession.");
}).catch((error)=>{
console.info("error:" + error.code + error.message);
});
``` ```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId()).then (()=>{
console.info("join session.");
}).catch((error)=>{
console.info("error:" + error.code + error.message);
});
// Exit the distributed network.
g_object.setSessionId().then (()=>{
console.log("leave all lession.");
}).catch((error)=>{
console.info("error:" + error.code + error.message);
});
```
### on('change') ### on('change')<sup>9+</sup>
on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Subscribes to the changes of this distributed data object. Subscribes to the data change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
changeData.forEach(element => {
console.info("changed !" + element + " " + g_object[element]);
});
}
}
g_object.on("change", globalThis.changeCallback);
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => { globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId); console.info("change" + sessionId);
if (changeData != null && changeData != undefined) { if (changeData != null && changeData != undefined) {
...@@ -148,81 +377,161 @@ globalThis.changeCallback = (sessionId, changeData) => { ...@@ -148,81 +377,161 @@ globalThis.changeCallback = (sessionId, changeData) => {
g_object.on("change", globalThis.changeCallback); g_object.on("change", globalThis.changeCallback);
``` ```
### off('change') ### off('change')<sup>9+</sup>
off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Unsubscribes from the changes of this distributed data object. Unsubscribes from the data change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks.
g_object.off("change");
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Unregister the specified data change callback. // Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback); g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks. // Unregister all data change callbacks.
g_object.off("change"); g_object.off("change");
``` ```
### on('status') ### on('status')<sup>9+</sup>
on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void
Subscribes to the status change (online or offline) of this distributed data object. Subscribes to the status change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.| | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback); g_object.on("status", globalThis.statusCallback);
``` ```
### off('status') Stage model:
off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void ```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback);
```
### off('status')<sup>9+</sup>
off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void
Unsubscribes from the status change (online or offline) of this distributed data object. Unsubscribes from the status change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.| | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
// Unsubscribe from the specified status change callback for the distributed data object. // Unsubscribe from the specified status change callback for the distributed data object.
g_object.off("status",globalThis.statusCallback); g_object.off("status",globalThis.statusCallback);
// Unregister all status change callbacks.
g_object.off("status");
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
// Unsubscribe from all status change callbacks for the distributed data object. // Unsubscribe from all status change callbacks for the distributed data object.
g_object.off("status",globalThis.statusCallback);
// Unregister all status change callbacks.
g_object.off("status"); g_object.off("status");
``` ```
...@@ -243,18 +552,44 @@ The saved data will be released in the following cases: ...@@ -243,18 +552,44 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| | callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example** **Example**
```js
FA model:
```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.save("local", (status, result)=>{ g_object.save("local", (result) => {
console.log("save status = " + status); console.log("save callback");
console.info("save sessionId: " + result.sessionId);
console.info("save version: " + result.version);
console.info("save deviceId: " + result.deviceId);
});
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local", (result) => {
console.log("save callback"); console.log("save callback");
console.info("save sessionId: " + result.sessionId); console.info("save sessionId: " + result.sessionId);
console.info("save version: " + result.version); console.info("save version: " + result.version);
...@@ -279,6 +614,7 @@ The saved data will be released in the following cases: ...@@ -279,6 +614,7 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
...@@ -291,16 +627,44 @@ The saved data will be released in the following cases: ...@@ -291,16 +627,44 @@ The saved data will be released in the following cases:
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.save("local").then((result)=>{ g_object.save("local").then((result) => {
console.log("save callback"); console.log("save callback");
console.info("save sessionId " + result.sessionId); console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version); console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId); console.info("save deviceId " + result.deviceId);
}, ()=>{ }, () => {
console.error("save failed");
});
```
Stage model:
```js
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
}
let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local").then((result) => {
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, () => {
console.error("save failed"); console.error("save failed");
}); });
``` ```
...@@ -317,18 +681,61 @@ If the object is stored on another device, the data on the local device will be ...@@ -317,18 +681,61 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| | callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.revokeSave((result, data) =>{ // Save data for persistence.
g_object.save("local", (result) => {
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
});
// Delete the persistence data.
g_object.revokeSave((result) => {
console.log("revokeSave callback"); console.log("revokeSave callback");
console.log("revokeSave sessionId " + result.sessionId);
});
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
// Save data for persistence.
g_object.save("local", (result) => {
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
});
// Delete the persistence data.
g_object.revokeSave((result) => {
console.log("revokeSave callback");
console.log("revokeSave sessionId " + result.sessionId);
}); });
``` ```
...@@ -351,14 +758,265 @@ If the object is stored on another device, the data on the local device will be ...@@ -351,14 +758,265 @@ If the object is stored on another device, the data on the local device will be
**Example** **Example**
```js FA model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
// Save data for persistence.
g_object.save("local").then((result) => {
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, () => {
console.error("save failed");
});
// Delete the persistence data.
g_object.revokeSave().then((result) => {
console.log("revokeSave callback");
console.log("sessionId" + result.sessionId);
}, () => {
console.error("revokeSave failed");
});
```
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context
}
}
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.revokeSave().then((result)=>{ g_object.save("local").then((result) => {
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, () => {
console.error("save failed");
});
// Delete the persistence data.
g_object.revokeSave().then((result) => {
console.log("revokeSave callback"); console.log("revokeSave callback");
console.log("sessionId" + result.sessionId); console.log("sessionId" + result.sessionId);
}, ()=>{ }, () => {
console.error("revokeSave failed"); console.error("revokeSave failed");
}); });
``` ```
## distributedObject.createDistributedObject<sup>(deprecated)</sup>
createDistributedObject(source: object): DistributedObject
Creates a distributed data object.
> **NOTE**<br/>
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use **distributedObject.create**.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attributes of the distributed data object.|
**Return value**
| Type| Description|
| -------- | -------- |
| [DistributedObject](#distributedobjectdeprecated) | Distributed data object created.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
```
## DistributedObject<sup>(deprecated)</sup>
Provides APIs for managing a distributed data object.
### setSessionId<sup>(deprecated)</sup>
setSessionId(sessionId?: string): boolean
Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network.
> **NOTE**<br/>
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setSessionId](#setsessionid9).
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});;
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId());
// Remove g_object from the distributed network.
g_object.setSessionId("");
```
### on('change')<sup>(deprecated)</sup>
on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Subscribes to data changes of this distributed data object.
> **NOTE**<br/>
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('change')](#onchange9).
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
changeData.forEach(element => {
console.info("changed !" + element + " " + g_object[element]);
});
}
}
g_object.on("change", globalThis.changeCallback);
```
### off('change')<sup>(deprecated)</sup>
off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Unsubscribes from the data changes of this distributed data object.
> **NOTE**<br/>
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('change')](#offchange9).
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes. |
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks.
g_object.off("change");
```
### on('status')<sup>(deprecated)</sup>
on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void
Subscribes to status changes of this distributed data object.
> **NOTE**<br/>
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('status')](#onstatus9).
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback);
```
### off('status')<sup>(deprecated)</sup>
off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void
Unsubscribes from the status change of this distributed data object.
> **NOTE**<br/>
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('status')](#offstatus9) instead.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object. |
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
// Unregister the specified status change callback.
g_object.off("status",globalThis.statusCallback);
// Unregister all status change callbacks.
g_object.off("status");
```
...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re ...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
...@@ -69,9 +69,9 @@ Stage model: ...@@ -69,9 +69,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -103,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result ...@@ -103,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
**Return value** **Return value**
...@@ -139,9 +139,9 @@ Stage model: ...@@ -139,9 +139,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. | | name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -215,9 +215,9 @@ Stage model: ...@@ -215,9 +215,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.| | name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value** **Return value**
...@@ -294,9 +294,9 @@ Stage model: ...@@ -294,9 +294,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. | | name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -358,9 +358,9 @@ Stage model: ...@@ -358,9 +358,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.| | name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value** **Return value**
...@@ -428,9 +428,9 @@ Stage model: ...@@ -428,9 +428,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -662,7 +662,7 @@ try { ...@@ -662,7 +662,7 @@ try {
has(key: string, callback: AsyncCallback&lt;boolean&gt;): void has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.. Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -698,7 +698,7 @@ try { ...@@ -698,7 +698,7 @@ try {
has(key: string): Promise&lt;boolean&gt; has(key: string): Promise&lt;boolean&gt;
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.. Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -987,7 +987,7 @@ Unsubscribes from data changes. ...@@ -987,7 +987,7 @@ Unsubscribes from data changes.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ------------------------------------------ | | -------- | -------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | | type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. |
| callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| | callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, all callbacks for data changes will be unregistered. |
**Example** **Example**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册