提交 650959dd 编写于 作者: W wangshuainan1 提交者: Gitee

Merge branch 'OpenHarmony-3.1-Release' of gitee.com:openharmony/docs into OpenHarmony-3.1-Release

Signed-off-by: Nwangshuainan1 <wangshuainan1@huawei.com>
...@@ -6,6 +6,7 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -6,6 +6,7 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
...@@ -13,13 +14,13 @@ For details about the APIs related to distributed data, see [Distributed Data Ma ...@@ -13,13 +14,13 @@ For details about the APIs related to distributed data, see [Distributed Data Ma
| 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; | Obtains a KV store with the specified **Options** and **storeId**.| | 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; | Obtains a KV store with the specified **Options** and **storeId**.|
| 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> | Queries 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, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
...@@ -29,19 +30,50 @@ For details about the APIs related to distributed data, see [Distributed Data Ma ...@@ -29,19 +30,50 @@ For details about the APIs related to distributed data, see [Distributed Data Ma
The following uses a single KV store as an example to describe the development procedure. The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module. 1. Import the distributed data module.
```js ```js
import distributedData from '@ohos.data.distributedData'; import distributedData from '@ohos.data.distributedData';
``` ```
2. Apply for the required permission if data synchronization is required.
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. You need to configure the request permission in the **config.json** file. The sample code is as follows:
(1) Create a **KvManagerConfig** object based on the application context. ```json
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
```js
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
}
grantPermission();
```
3. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **kvManagerConfig** object based on the application context.
2. Create a **kvManager** instance.
(2) Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
```js
```
let kvManager; let kvManager;
try { try {
const kvManagerConfig = { const kvManagerConfig = {
...@@ -63,13 +95,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -63,13 +95,11 @@ The following uses a single KV store as an example to describe the development p
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error:" + e);
} }
``` ```
3. Create and obtain a single KV store.
(1) Declare the ID of the single KV store to create. 4. Create and obtain a single KV store.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. 1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (`autoSync:false`) and call `sync` when a synchronization is required.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -99,8 +129,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -99,8 +129,9 @@ The following uses a single KV store as an example to describe the development p
> **NOTE** > **NOTE**
> >
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. > For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
5. Subscribe to changes in the distributed data.
4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store: The following is the sample code for subscribing to the data changes of a single KV store:
```js ```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
...@@ -108,11 +139,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -108,11 +139,10 @@ The following uses a single KV store as an example to describe the development p
}); });
``` ```
5. Write data to the single KV store. 6. Write data to the single KV store.
(1) Construct the key and value to be written into the single KV store. 1. Construct the `Key` and `Value` to be written into the single KV store.
2. Write key-value pairs into the single KV store.
(2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store: The following is the sample code for writing key-value pairs of the string type into the single KV store:
...@@ -132,11 +162,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -132,11 +162,10 @@ The following uses a single KV store as an example to describe the development p
} }
``` ```
6. Query data in the single KV store. 7. Query data in the single KV store.
(1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store. 1. Construct the `Key` to be queried from the single KV store.
2. Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store: The following is the sample code for querying data of the string type from the single KV store:
```js ```js
...@@ -158,7 +187,8 @@ The following uses a single KV store as an example to describe the development p ...@@ -158,7 +187,8 @@ The following uses a single KV store as an example to describe the development p
} }
``` ```
7. Synchronize data to other devices.<br/> 8. Synchronize data to other devices.
Select the devices in the same network and the synchronization mode to synchronize data. Select the devices in the same network and the synchronization mode to synchronize data.
> **NOTE** > **NOTE**
......
# Distributed Data Service Overview # Distributed Data Service Overview
The distributed data service (DDS) implements distributed database collaboration across devices for applications. The distributed data service (DDS) implements distributed database collaboration across devices for applications.
Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices.
You do not need to care about the implementation of the database locking mechanism. You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts ## Basic Concepts
- **KV data model** ### KV Data Model
The key-value \(KV\) data model allows data to be organized, indexed, and stored in key-value pairs. The key-value (KV) data model allows data to be organized, indexed, and stored in KV pairs.
The KV data model is suitable for storing service data that is not related. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles database version compatibility issues and data synchronization conflicts easily. The distributed database is based on the KV data model and provides KV-based access interfaces. The KV data model is suitable for storing service data that is not related. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles database version compatibility issues and data synchronization conflicts easily. The distributed database is based on the KV data model and provides KV-based access interfaces.
- **Distributed database transactions** ### Distributed Database Transaction
Distributed database transactions include local transactions \(same as the transactions of traditional databases\) and synchronization transactions. Synchronization transactions allow data to be synchronized between devices by local transaction. Synchronization of a local transaction modification either succeeds or fails on all the devices. Distributed database transactions include local transactions (same as the transactions of traditional databases) and synchronization transactions. Synchronization transactions allow data to be synchronized between devices by local transaction. Synchronization of a local transaction modification either succeeds or fails on all the devices.
- **Distributed database consistency** ### Distributed Database Consistency
In a distributed scenario, cross-device collaboration demands consistent data between the devices in the same network. The data consistency can be classified into the following types: In a distributed scenario, cross-device collaboration demands consistent data between the devices in the same network. The data consistency can be classified into the following types:
- **Strong consistency**: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately. - **Strong consistency**: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately.
- **Weak consistency**: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the latest data. The data on these devices may be inconsistent after a certain period of time. - **Weak consistency**: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the latest data. The data on these devices may be inconsistent after a certain period of time.
- **Eventual consistency**: When data is added, deleted, or modified on a device, other devices in the same network may not obtain the latest data immediately. However, data on these devices will become consistent after a certain period of time. - **Eventual consistency**: When data is added, deleted, or modified on a device, other devices in the same network may not obtain the latest data immediately. However, data on these devices will become consistent after a certain period of time.
Strong consistency has high requirements on distributed data management and may be used in distributed server deployment. The DDS supports only the eventual consistency because mobile devices are not always online and the network has no center. Strong consistency has high requirements on distributed data management and may be used in distributed server deployment. The DDS supports only the eventual consistency because mobile devices are not always online and the network has no center.
- **Distributed database synchronization** ### Distributed Database Synchronization
After discovering and authenticating a device, the underlying communication component notifies the upper-layer application \(including the DDS\) that the device goes online. The DDS then establishes an encrypted transmission channel to synchronize data between the two devices. After discovering and authenticating a device, the underlying communication component notifies the upper-layer application (including the DDS) that the device goes online. The DDS then establishes an encrypted transmission channel to synchronize data between the two devices.
The DDS provides the following synchronization modes: The DDS provides the following synchronization modes:
- **Manual synchronization**: Applications call **sync** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL\_ONLY** \(pulling remote data to the local end\), **PUSH\_ONLY** \(pushing local data to the remote end\), or **PUSH\_PULL** \(pushing local data to the remote end and pulling remote data to the local end\). The internal interface supports condition-based synchronization. The data that meets the conditions can be synchronized to the remote end. - **Manual synchronization**: Applications call **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). The internal interface supports condition-based synchronization. The data that meets the conditions can be synchronized to the remote end.
- **Automatic synchronization**: includes full synchronization and condition-based subscription synchronization. In full synchronization, the distributed database automatically pushes local data to the remote end and pulls remote data to the local end when a device goes online or application data is updated. Applications do not need to call **sync**. The internal interface supports condition-based subscription synchronization. The data that meets the subscription conditions on the remote end is automatically synchronized to the local end. - **Automatic synchronization**: includes full synchronization and condition-based subscription synchronization. In full synchronization, the distributed database automatically pushes local data to the remote end and pulls remote data to the local end when a device goes online or application data is updated. Applications do not need to call **sync()**. The internal interface supports condition-based subscription synchronization. The data that meets the subscription conditions on the remote end is automatically synchronized to the local end.
- **Single KV store** ### Single KV Store
Data is saved locally in the unit of a single KV entry. Only one entry is saved for each key. Data can be modified only locally and synchronized to remote devices in sequence based on the update time. Data is saved locally in the unit of a single KV entry. Only one entry is saved for each key. Data can be modified only locally and synchronized to remote devices in sequence based on the update time.
- **Device KV store** ### Device KV Store
The device KV store is based on the single KV store. The local device ID is added to the key when KV data is stored in the device KV store. Data can be isolated, managed, and queried by device. However, the data synchronized from remote devices cannot be modified locally. The device KV store is based on the single KV store. The local device ID is added to the key when KV data is stored in the device KV store. Data can be isolated, managed, and queried by device. However, the data synchronized from remote devices cannot be modified locally.
- **Conflict resolution** ### Conflict Resolution
A data conflict occurs when multiple devices modify the same data and commit the modification to the database. The last write wins \(LWW\) is the default conflict resolution policy used for data conflicts. Based on the commit timestamps, the data with a later timestamp is used. Currently, customized conflict resolution policies are not supported. A data conflict occurs when multiple devices modify the same data and commit the modification to the database. The last write wins (LWW) is the default conflict resolution policy used for data conflicts. Based on the commit timestamps, the data with a later timestamp is used. Currently, customized conflict resolution policies are not supported.
- **Schema-based database management and data query based on predicates** ### Schema-based Database Management and Predicate-based Data Query
A schema is specified when you create or open a single KV store. Based on the schema, the database detects the value format of key-value pairs and checks the value structure. Based on the fields in the values, the database implements index creation and predicate-based query. A schema is specified when you create or open a single KV store. Based on the schema, the database detects the value format of KV pairs and checks the value structure. Based on the fields in the values, the database implements index creation and predicate-based query.
- **Distributed database backup** ### Distributed Database Backup
The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases.
## Working Principles ## Working Principles
The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices.
- **APIs** The DDS consists of the following:
The DDS provides APIs to create databases, access data, and subscribe to data. The APIs support the KV data model and common data types. They are highly compatible and easy to use, and can be released. - **APIs**<br>The DDS provides APIs to create databases, access data, and subscribe to data. The APIs support the KV data model and common data types. They are highly compatible and easy to use, and can be released.
- **Service component** - **Service component**<br>The service component implements management of metadata, permissions, encryption, backup and restore, and multiple users, and completes initialization of the storage component, synchronization component, and communication adaptation layer of the distributed database.
The service component implements management of metadata, permissions, encryption, backup and restore, and multiple users, and completes initialization of the storage component, synchronization component, and communication adaptation layer of the distributed database. - **Storage component**<br>The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution.
- **Storage component** - **Synchronization component**<br>The synchronization component interacts with the storage component and the communication adaptation layer to maintain data consistency between online devices. It synchronizes data generated on the local device to other devices and merges data from other devices into the local device.
The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution. - **Communication adaptation layer**<br>The communication adaptation layer calls APIs of the underlying public communication layer to create and connect to communication channels, receive device online and offline messages, update metadata of the connected and disconnected devices, send device online and offline messages to the synchronization component. The synchronization component updates the list of connected devices, and calls the APIs of the communication adaption layer to encapsulate data and send the data to the connected devices.
- **Synchronization component** Applications call the DDS APIs to create, access, and subscribe to distributed databases. The APIs store data to the storage component based on the capabilities provided by the service component. The storage component interacts with the synchronization component to synchronize data. The synchronization component uses the communication adaptation layer to synchronize data to remote devices, which update the data in the storage component and provide the data for applications through service APIs.
The synchronization component interacts with the storage component and the communication adaptation layer to maintain data consistency between online devices. It synchronizes data generated on the local device to other devices and merges data from other devices into the local device.
- **Communication adaptation layer** **Figure 1** How DDS works
The communication adaptation layer calls APIs of the underlying public communication layer to create and connect to communication channels, receive device online and offline messages, update metadata of the connected and disconnected devices, send device online and offline messages to the synchronization component. The synchronization component updates the list of connected devices, and calls the APIs of the communication adaption layer to encapsulate data and send the data to the connected devices.
![](figures/en-us_image_0000001183386164.png)
Applications call the DDS APIs to create, access, and subscribe to distributed databases. The APIs store data to the storage component based on the capabilities provided by the service component. The storage component interacts with the synchronization component to synchronize data. The synchronization component uses the communication adaptation layer to synchronize data to remote devices, which update the data in the storage component and provide the data for applications through service APIs.
**Figure 1** How DDS works<a name="fig9151258063"></a> ## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
![](figures/en-us_image_0000001183386164.png) - The KV data model specifications supported by the DDS are as follows:
## Constraints - For each record in a device KV store, the key must be less than or equal to 896 bytes and the value be less than 4 MB.
- For each record in a single KV store, the key must be less than or equal to 1 KB and the value be less than 4 MB.
- An application can open a maximum of 16 KV stores simultaneously.
- The data that needs to be synchronized between devices should be stored in distributed databases rather than local databases.
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The DDS does not support customized conflict resolution policies.
- The KV data model specifications supported by the DDS are as follows:
- For each record in a device KV store, the key must be less than or equal to 896 bytes and the value be less than 4 MB.
- For each record in a single KV store, the key must be less than or equal to 1 KB and the value be less than 4 MB.
- An application can open a maximum of 16 KV stores simultaneously.
- The data that needs to be synchronized between devices should be stored in distributed databases rather than local databases. - The maximum number of access requests to the KvStore API is 1000 per second and 10000 per minute. The maximum number of access requests to the KvManager API is 50 per second and 500 per minute.
- The DDS does not support customized conflict resolution policies.
- The maximum number of access requests to the KvStore API is 1000 per second and 10000 per minute. The maximum number of access requests to the KvManager API is 50 per second and 500 per minute.
- Blocking operations, such as modifying UI components, are not allowed in the distributed database event callback.
- Blocking operations, such as modifying UI components, are not allowed in the distributed database event callback.
...@@ -16,8 +16,8 @@ The table below describes the APIs available for creating and deleting an RDB st ...@@ -16,8 +16,8 @@ The table below describes the APIs available for creating and deleting an RDB st
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
|getRdbStore(config:StoreConfig,version:number):Promise&lt;RdbStore&gt; | Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.<br>- **config**: configuration of the RDB store.<br>- **version**: version of the RDB store.| |getRdbStore(config: StoreConfig, version: number): Promise&lt;RdbStore&gt; | Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.<br>- **config**: configuration of the RDB store.<br>- **version**: version of the RDB store.|
| deleteRdbStore(name:string):Promise&lt;void&gt; | Deletes an RDB store. This API uses a promise to return the result.<br>- **name**: name of the RDB store to delete.| | deleteRdbStore(name: string): Promise&lt;void&gt; | Deletes an RDB store. This API uses a promise to return the result.<br>- **name**: name of the RDB store to delete.|
### Managing Data in an RDB Store ### Managing Data in an RDB Store
...@@ -31,7 +31,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying ...@@ -31,7 +31,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | insert(name:string,values:ValuesBucket):Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.<br>- **name**: name of the target table.<br>- **values**: data to be inserted into the table.| | RdbStore | insert(name: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.<br>- **name**: name of the target table.<br>- **values**: data to be inserted into the table.|
- **Updating Data** - **Updating Data**
...@@ -41,7 +41,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying ...@@ -41,7 +41,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | update(values:ValuesBucket,rdbPredicates:RdbPredicates):Promise\<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **rdbPredicates**: conditions for updating data.| | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise\<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **rdbPredicates**: conditions for updating data.|
- **Deleting Data** - **Deleting Data**
...@@ -51,7 +51,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying ...@@ -51,7 +51,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | delete(rdbPredicates:RdbPredicates):Promise\<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **rdbPredicates**: conditions for deleting data.| | RdbStore | delete(rdbPredicates: RdbPredicates): Promise\<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **rdbPredicates**: conditions for deleting data.|
- **Querying data** - **Querying data**
...@@ -64,8 +64,8 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying ...@@ -64,8 +64,8 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | query(rdbPredicates:RdbPredicates,columns:Array):Promise&lt;ResultSet&gt; | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.<br>- **rdbPredicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise&lt;ResultSet&gt; | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.<br>- **rdbPredicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
| RdbStore | querySql(sql:string,bindArgs?:Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt; | Queries data using the specified SQL statement. This API uses a promise to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.| | RdbStore | querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;): Promise&lt;ResultSet&gt; | Queries data using the specified SQL statement. This API uses a promise to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.|
### Using Predicates ### Using Predicates
...@@ -77,11 +77,11 @@ The table below lists common predicates. For more information about predicates, ...@@ -77,11 +77,11 @@ The table below lists common predicates. For more information about predicates,
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.| | RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.| | RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.| | RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.|
| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.| | RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.|
| RdbPredicates | contains(field:string,value:string):RdbPredicats | Sets an **RdbPredicates** object to match a string that contains the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.| | RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets an **RdbPredicates** object to match a string that contains the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
### Using the Result Set ### Using the Result Set
...@@ -97,12 +97,12 @@ For details about how to use result set APIs, see [Result Set](../reference/apis ...@@ -97,12 +97,12 @@ For details about how to use result set APIs, see [Result Set](../reference/apis
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ResultSet | goToFirstRow():boolean | Moves to the first row of the result set.| | ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set.|
| ResultSet | getString(columnIndex:number):string | Obtains the value in the form of a string based on the specified column and current row.| | ResultSet | getString(columnIndex:number): string | Obtains the value in the form of a string based on the specified column and current row.|
| ResultSet | getBlob(columnIndex:number):Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| | ResultSet | getBlob(columnIndex:number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.|
| ResultSet | getDouble(columnIndex:number):number | Obtains the value in the form of double based on the specified column and current row.| | ResultSet | getDouble(columnIndex:number): number | Obtains the value in the form of double based on the specified column and current row.|
| ResultSet | getLong(columnIndex:number):number | Obtains the value in the form of a long integer based on the specified column and current row. | | ResultSet | getLong(columnIndex:number): number | Obtains the value in the form of a long integer based on the specified column and current row. |
| ResultSet | close():void | Closes the result set.| | ResultSet | close(): void | Closes the result set.|
...@@ -148,7 +148,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -148,7 +148,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.| | RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This method uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.|
## How to Develop ## How to Develop
......
...@@ -90,9 +90,9 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -90,9 +90,9 @@ Use the following APIs to delete a **Storage** instance or data file.
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromsie====================>");
let promise = dataStorage.getStorage(path + '/mystore');
}); });
let promise = dataStorage.getStorage(path + '/mystore');
``` ```
...@@ -118,18 +118,19 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -118,18 +118,19 @@ Use the following APIs to delete a **Storage** instance or data file.
Use the **get\(\)** method of the **Storage** class to read data. Use the **get\(\)** method of the **Storage** class to read data.
```js ```js
promise.then((storage) => { promise.then((storage) => {
let getPromise = storage.get('startup', 'default'); let getPromise = storage.get('startup', 'default')
getPromise.then((value) => { getPromise.then((value) => {
console.info("The value of startup is " + value); console.info("The value of startup is " + value);
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the value of startup with err: " + err); console.info("Failed to get the value of startup with err: " + err);
}) })
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the storage."); console.info("Failed to get the storage.")
})
``` })
```
5. Store data persistently. 5. Store data persistently.
...@@ -144,32 +145,32 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -144,32 +145,32 @@ Use the following APIs to delete a **Storage** instance or data file.
Specify **StorageObserver** as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush\(\)** method is executed, **StorageObserver** will be invoked. Unregister the **StorageObserver** when it is no longer required. Specify **StorageObserver** as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush\(\)** method is executed, **StorageObserver** will be invoked. Unregister the **StorageObserver** when it is no longer required.
```js ```js
promise.then((storage) => { promise.then((storage) => {
var observer = function (key) { var observer = function (key) {
console.info("The key of " + key + " changed."); console.info("The key of " + key + " changed.");
} }
storage.on('change', observer); storage.on('change', observer)
storage.putSync('startup', 'auto'); // Modify data in the Storage instance. storage.putSync('startup', 'auto'); // Modify data in the Storage instance.
storage.flushSync(); // Trigger the StorageObserver callback. storage.flushSync(); // Trigger the StorageObserver callback.
storage.off('change', observer); // Unsubscribe from the data changes. storage.off('change', observer); // Unsubscribe from the data changes.
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the storage."); console.info("Failed to get the storage.");
}) })
``` ```
7. Delete the specified file. 7. Delete the specified file.
Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored. Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
```js ```js
let promise = dataStorage.deleteStorage(path + '/mystore'); let promise = dataStorage.deleteStorage(path + '/mystore');
promise.then(() => { promise.then(() => {
console.info("Succeeded in deleting the storage."); console.info("Succeeded in deleting the storage.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to deleted the storage with err: " + err); console.info("Failed to delete the storage with err: " + err);
})
``` })
```
...@@ -26,58 +26,30 @@ ...@@ -26,58 +26,30 @@
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.| | ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.| | ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorType, callback:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.| | ohos.sensor | sensor.off(sensorType, callback?:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.|
## How to Develop ## How to Develop
1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file. 1. Before obtaining data from a type of sensor, check whether the required permission has been configured.<br>
The system provides the following sensor-related permissions:
``` - ohos.permission.ACCELEROMETER
"reqPermissions":[
{ - ohos.permission.GYROSCOPE
"name":"ohos.permission.ACCELEROMETER",
"reason":"", - ohos.permission.ACTIVITY_MOTION
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"], - ohos.permission.READ_HEALTH_DATA
"when":"inuse"
} For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
},
{
"name":"ohos.permission.GYROSCOPE",
"reason":"",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
{
"name":"ohos.permission.ACTIVITY_MOTION",
"reason":"ACTIVITY_MOTION_TEST",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
{
"name":"ohos.permission.READ_HEALTH_DATA",
"reason":"HEALTH_DATA_TEST",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
]
```
2. Subscribe to data changes of a type of sensor. 2. Subscribe to data changes of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data){
console.info("Subscription succeeded. data = "+ data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
} });
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -87,11 +59,8 @@ ...@@ -87,11 +59,8 @@
3. Unsubscribe from sensor data changes. 3. Unsubscribe from sensor data changes.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER);
console.info("Succeeded in unsubscribing from acceleration sensor data."); // The unsubscription is successful, and the result is printed.
}
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -101,11 +70,10 @@ ...@@ -101,11 +70,10 @@
4. Subscribe to only one data change of a type of sensor. 4. Subscribe to only one data change of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
} });
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -115,11 +83,12 @@ ...@@ -115,11 +83,12 @@
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example: If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example:
``` ```
import sensor from "@ohos.sensor";
try { try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
}); });
} catch (error) { } catch (error) {
console.error(error); console.error("Failed to get sensor data");
} }
``` ```
\ No newline at end of file
...@@ -6,29 +6,29 @@ Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your ap ...@@ -6,29 +6,29 @@ Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your ap
A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows: A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows:
| Type | Name | Description | Usage | | Type | Name | Description | Usage |
| --------------------------------------- | ------------------ | ------------------------------------------------------------ | ---------------------------------------- | | --------------------------------------- | --------- | ---------------------------------------- | -------------------- |
| SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status | | SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status |
| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation | | SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation |
| SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis | | SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis |
| SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity | | SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity |
| SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity | | SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity |
| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity | | SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity |
| SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device | | SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device |
| SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step | | SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step |
| SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked | | SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked |
| SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature | | SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature |
| SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass | | SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass |
| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation | | SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation |
| SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity | | SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity |
| SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar. | Measuring the barometric pressure | | SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar.| Measuring the barometric pressure |
| SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad.| Providing the three orientation angles of the screen | | SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad. | Providing the three orientation angles of the screen |
| SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor.| Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system | | SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor. | Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system |
| SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call | | SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call |
| SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top| | SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top|
| SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data | | SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data |
| SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables | | SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables |
| SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device | | SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device |
## Working Principles ## Working Principles
...@@ -52,15 +52,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso ...@@ -52,15 +52,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
1. To obtain data of the following sensors, you must claim the required permissions. 1. To obtain data of the following sensors, you must claim the required permissions.
Table 7 Sensor data permissions | Sensor | Permission | Sensitivity | Permission Description |
| ------------------------- | -------------------------------- | ------------ | ----------------------- |
| Sensor | Permission | Sensitivity | Permission Description | | Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.|
| ------------------------- | -------------------------------- | ------------ | ----------------------- | | Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.|
| Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.| | Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.| | Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
| Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting. 2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting.
\ No newline at end of file
...@@ -21,16 +21,16 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -21,16 +21,16 @@ The following table lists the USB APIs currently available. For details, see the
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. | | bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. |
| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. | | getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. |
| controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise\<number> | Performs control transfer. | | controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise\<number> | Performs control transfer. |
## How to Develop ## How to Develop
You can set a USB device as a host to connect to a device for data transfer. The development procedure is as follows: You can set a USB device as the USB host to connect to other USB devices for data transfer. The development procedure is as follows:
1. Obtain the USB device list. 1. Obtain the USB device list.
......
...@@ -10,77 +10,42 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -10,77 +10,42 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
## Available APIs ## Available APIs
| Module| API| Description| | Module | API | Description |
| -------- | -------- | -------- | | ------------- | ---------------------------------------- | ------------------------------- |
| ohos.vibrator | vibrate(duration: number): Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result.| | ohos.vibrator | vibrate(duration: number): Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified duration. This API uses a callback to return the result.| | ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified duration. This API uses a callback to return the result. |
| ohos.vibrator | vibrate(effectId: EffectId): Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result.| | ohos.vibrator | vibrate(effectId: EffectId): Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| | ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified effect. This API uses a callback to return the result.|
| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration. This API uses a promise to return the result.| | ohos.vibrator | stop(stopMode: VibratorStopMode): Promise&lt;void&gt;| Stops vibration. This API uses a promise to return the result. |
| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. This API uses a callback to return the result.| | ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. This API uses a callback to return the result. |
## How to Develop ## How to Develop
1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file. 1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
```
"reqPermissions": [
{
"name": "ohos.permission.ACCELEROMETER",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.VIBRATE",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
]
```
2. Trigger the device to vibrate. 2. Trigger the device to vibrate.
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error)=>{ vibrator.vibrate(1000).then((error) => {
if (error){ // The call fails, and error.code and error.message are printed. if (error) { // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
}else{ // The call is successful, and the device starts to vibrate. } else { // The call is successful, and the device starts to vibrate.
Console.log("Promise returned to indicate a successful vibration.") console.log("Promise returned to indicate a successful vibration.")
}; }
}) })
``` ```
3. Stop the vibration. 3. Stop the vibration.
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => {
if(error){ // The call fails, and error.code and error.message are printed. if (error) { // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
}else{ // The call is successful, and the device stops vibrating. } else { // The call is successful, and the device stops vibrating.
Console.log("Promise returned to indicate a successful stop."); console.log("Promise returned to indicate successful.");
}; }
}) })
``` ```
...@@ -10,7 +10,7 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -10,7 +10,7 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
**Figure 1** Vibrator in Misc devices **Figure 1** Vibrator in Misc devices
![en-us_image_0000001180249428.png](figures/en-us_image_0000001180249428.png) ![0752d302-aeb9-481a-bb8f-e5524eb61eeb](figures/0752d302-aeb9-481a-bb8f-e5524eb61eeb.png)
- Vibrator API: provides basic vibrator APIs, including the APIs for obtaining the vibrator list, querying the vibrator by effect, and triggering and stopping vibration. - Vibrator API: provides basic vibrator APIs, including the APIs for obtaining the vibrator list, querying the vibrator by effect, and triggering and stopping vibration.
...@@ -23,4 +23,7 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -23,4 +23,7 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
## Constraints ## Constraints
When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**. When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect.
...@@ -29,7 +29,7 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul ...@@ -29,7 +29,7 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or function.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | [Context](js-apis-Context.md) | Yes| Application context.|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
| callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.| | callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.|
...@@ -37,8 +37,13 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul ...@@ -37,8 +37,13 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul
**Example** **Example**
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db"} const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
if (err) { if (err) {
console.info("Failed to get RdbStore, err: " + err) console.info("Failed to get RdbStore, err: " + err)
return return
...@@ -59,7 +64,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set ...@@ -59,7 +64,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or function.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | [Context](js-apis-Context.md) | Yes| Application context.|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
...@@ -72,8 +77,13 @@ Obtains an RDB store. This API uses a promise to return the result. You can set ...@@ -72,8 +77,13 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
**Example** **Example**
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db" } const STORE_CONFIG = { name: "RdbTest.db" }
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1); let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1);
promise.then(async (rdbStore) => { promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
...@@ -92,13 +102,18 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul ...@@ -92,13 +102,18 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or function.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | [Context](js-apis-Context.md) | Yes| Application context.|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
```js ```js
data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) { if (err) {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
return return
...@@ -118,7 +133,7 @@ Deletes an RDB store. This API uses a promise to return the result. ...@@ -118,7 +133,7 @@ Deletes an RDB store. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or function.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | [Context](js-apis-Context.md) | Yes| Application context.|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
**Return value** **Return value**
...@@ -128,7 +143,12 @@ Deletes an RDB store. This API uses a promise to return the result. ...@@ -128,7 +143,12 @@ Deletes an RDB store. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
...@@ -166,7 +186,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -166,7 +186,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
inDevices(devices: Array&lt;string&gt;): RdbPredicates inDevices(devices: Array&lt;string&gt;): RdbPredicates
Connects to the specified remote devices on the network during distributed database synchronization. Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -191,7 +211,7 @@ predicates.inDevices(['12345678abcde']) ...@@ -191,7 +211,7 @@ predicates.inDevices(['12345678abcde'])
inAllDevices(): RdbPredicates inAllDevices(): RdbPredicates
Connects to all remote devices on the network during distributed database synchronization. Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -780,14 +800,7 @@ Sets an **RdbPredicates** to filter out duplicate records. ...@@ -780,14 +800,7 @@ Sets an **RdbPredicates** to filter out duplicate records.
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct("NAME") predicates.equalTo("NAME", "Rose").distinct()
let promise = rdbStore.query(predicates, ["NAME"])
promise.then((resultSet) => {
console.log("resultSet column names:" + resultSet.columnNames)
console.log("resultSet column count:" + resultSet.columnCount)
}).catch((err) => {
console.log("query err.")
})
``` ```
...@@ -1434,7 +1447,7 @@ try { ...@@ -1434,7 +1447,7 @@ try {
setDistributedTables(tables: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void setDistributedTables(tables: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void
Sets a list of distributed tables. This API uses an asynchronous callback to return the result. Sets distributed tables. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1460,7 +1473,7 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { ...@@ -1460,7 +1473,7 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) {
setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt; setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt;
Sets a list of distributed tables. This API uses a promise to return the result. Sets distributed tables. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
......
...@@ -250,7 +250,7 @@ Closes a KV store. This API uses an asynchronous callback to return the result. ...@@ -250,7 +250,7 @@ Closes a KV store. This API uses an asynchronous callback to return the result.
| appId | string | Yes | Bundle name of the app that invokes the KV store. | | appId | string | Yes | Bundle name of the app that invokes the KV store. |
| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | | kvStore | [KVStore](#kvstore) | Yes | KV store to close. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.|
**Example** **Example**
...@@ -348,7 +348,7 @@ Deletes a KV store. This API uses an asynchronous callback to return the result. ...@@ -348,7 +348,7 @@ Deletes a KV store. This API uses an asynchronous callback to return the result.
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| appId | string | Yes | Bundle name of the app that invokes the KV store. | | appId | string | Yes | Bundle name of the app that invokes the KV store. |
| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.|
**Example** **Example**
...@@ -444,7 +444,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) ...@@ -444,7 +444,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore)
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| appId | string | Yes | Bundle name of the app that invokes the KV store. | | appId | string | Yes | Bundle name of the app that invokes the KV store. |
| callback | AsyncCallback&lt;string[]&gt; | Yes |Callback used to return the KV store IDs obtained. | | callback | AsyncCallback&lt;string[]&gt; | Yes |Callback invoked to return the KV store IDs obtained. |
**Example** **Example**
...@@ -513,7 +513,7 @@ Subscribes to service status changes. ...@@ -513,7 +513,7 @@ Subscribes to service status changes.
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| | event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.|
| deathCallback | Callback&lt;void&gt; | Yes | Callback used to return a service status change event.| | deathCallback | Callback&lt;void&gt; | Yes | Callback invoked to return a service status change event.|
**Example** **Example**
...@@ -596,16 +596,15 @@ Enumerates the KV store types. ...@@ -596,16 +596,15 @@ Enumerates the KV store types.
Enumerates the KV store security levels. Enumerates the KV store security levels.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Value| Description | | Name | Value| Description |
| --- | ---- | ----------------------- | | --- | ---- | ----------------------- |
| NO_LEVEL | 0 | No security level is set for the KV store. | | NO_LEVEL | 0 | No security level is set for the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| S0 | 1 | The KV store security level is public.| | S0 | 1 | The KV store security level is public.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| | S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| | S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| | S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| | S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
## Constants ## Constants
...@@ -2086,7 +2085,7 @@ Adds a KV pair of the specified type to this KV store. This API uses an asynchro ...@@ -2086,7 +2085,7 @@ Adds a KV pair of the specified type to this KV store. This API uses an asynchro
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | | value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). |
| callback | AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -2159,7 +2158,7 @@ Deletes a KV pair from this KV store. This API uses an asynchronous callback to ...@@ -2159,7 +2158,7 @@ Deletes a KV pair from this KV store. This API uses an asynchronous callback to
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
| callback | AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -2242,7 +2241,7 @@ Subscribes to data changes of the specified type. ...@@ -2242,7 +2241,7 @@ Subscribes to data changes of the specified type.
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | | event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. |
| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | | type |[SubscribeType](#subscribetype) | Yes |Type of data change. |
| observer |Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes |Callback used to return a data change event.| | observer |Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes |Callback invoked to return a data change event.|
**Example** **Example**
...@@ -2267,7 +2266,7 @@ Subscribes to synchronization complete events. ...@@ -2267,7 +2266,7 @@ Subscribes to synchronization complete events.
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | | event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. |
| syncCallback |Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes |Callback used to return a synchronization complete event. | | syncCallback |Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes |Callback invoked to return a synchronization complete event. |
**Example** **Example**
...@@ -2328,7 +2327,7 @@ Inserts KV pairs in batches to this KV store. This API uses an asynchronous call ...@@ -2328,7 +2327,7 @@ Inserts KV pairs in batches to this KV store. This API uses an asynchronous call
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
| callback |Asyncallback&lt;void&gt; |Yes |Callback used to return the result.| | callback |Asyncallback&lt;void&gt; |Yes |Callback invoked to return the result.|
**Example** **Example**
...@@ -2430,7 +2429,7 @@ Deletes KV pairs in batches from this KV store. This API uses an asynchronous ca ...@@ -2430,7 +2429,7 @@ Deletes KV pairs in batches from this KV store. This API uses an asynchronous ca
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| keys |string[] | Yes |KV pairs to delete in batches. | | keys |string[] | Yes |KV pairs to delete in batches. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -2532,7 +2531,7 @@ Starts the transaction in this KV store. This API uses an asynchronous callback ...@@ -2532,7 +2531,7 @@ Starts the transaction in this KV store. This API uses an asynchronous callback
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -2619,7 +2618,7 @@ Commits the transaction in this KV store. This API uses an asynchronous callback ...@@ -2619,7 +2618,7 @@ Commits the transaction in this KV store. This API uses an asynchronous callback
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -2681,7 +2680,7 @@ Rolls back the transaction in this KV store. This API uses an asynchronous callb ...@@ -2681,7 +2680,7 @@ Rolls back the transaction in this KV store. This API uses an asynchronous callb
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -2744,7 +2743,7 @@ Sets data synchronization, which can be enabled or disabled. This API uses an as ...@@ -2744,7 +2743,7 @@ Sets data synchronization, which can be enabled or disabled. This API uses an as
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | | enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -2814,7 +2813,7 @@ Sets the data synchronization range. This API uses an asynchronous callback to r ...@@ -2814,7 +2813,7 @@ Sets the data synchronization range. This API uses an asynchronous callback to r
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| localLabels |string[] | Yes |Synchronization labels set for the local device. | | localLabels |string[] | Yes |Synchronization labels set for the local device. |
| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | | remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -3141,7 +3140,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an ...@@ -3141,7 +3140,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| query |[Query](#query8) | Yes |Key prefix to match. | | query |[Query](#query8) | Yes |Key prefix to match. |
| callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes |Callback used to return the KV pairs obtained. | | callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes |Callback invoked to return the KV pairs obtained. |
**Example** **Example**
...@@ -3463,7 +3462,7 @@ Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet]( ...@@ -3463,7 +3462,7 @@ Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | | resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -3635,7 +3634,7 @@ Deletes data of a device. This API uses an asynchronous callback to return the r ...@@ -3635,7 +3634,7 @@ Deletes data of a device. This API uses an asynchronous callback to return the r
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes |ID of the target device. | | deviceId |string | Yes |ID of the target device. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -3824,7 +3823,7 @@ Sets the default delay allowed for KV store synchronization. This API uses an as ...@@ -3824,7 +3823,7 @@ Sets the default delay allowed for KV store synchronization. This API uses an as
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | | defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -3961,7 +3960,7 @@ Obtains a string value that matches the specified device ID and key. This API us ...@@ -3961,7 +3960,7 @@ Obtains a string value that matches the specified device ID and key. This API us
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes |ID of the target device. | | deviceId |string | Yes |ID of the target device. |
| key |string | Yes |Key to match. | | key |string | Yes |Key to match. |
| callback |AsyncCallback&lt;boolean\|string\|number\|Uint8Array&gt; | Yes |Callback used to return the value obtained. | | callback |AsyncCallback&lt;boolean\|string\|number\|Uint8Array&gt; | Yes |Callback invoked to return the value obtained. |
**Example** **Example**
...@@ -4040,7 +4039,7 @@ Obtains all KV pairs that match the specified device ID and key prefix. This API ...@@ -4040,7 +4039,7 @@ Obtains all KV pairs that match the specified device ID and key prefix. This API
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes |ID of the target device. | | deviceId |string | Yes |ID of the target device. |
| keyPrefix |string | Yes |Key prefix to match. | | keyPrefix |string | Yes |Key prefix to match. |
| callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes |Callback used to return the KV pairs obtained. | | callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes |Callback invoked to return the KV pairs obtained. |
**Example** **Example**
...@@ -4146,7 +4145,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an ...@@ -4146,7 +4145,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| query |[Query](#query8) | Yes |**Query** object to match. | | query |[Query](#query8) | Yes |**Query** object to match. |
| callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes |Callback used to return the KV pairs obtained. | | callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes |Callback invoked to return the KV pairs obtained. |
**Example** **Example**
...@@ -4682,7 +4681,7 @@ Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet]( ...@@ -4682,7 +4681,7 @@ Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | | resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
...@@ -4961,7 +4960,7 @@ Deletes data of the specified device from this KV store. This API uses an asynch ...@@ -4961,7 +4960,7 @@ Deletes data of the specified device from this KV store. This API uses an asynch
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes |ID of the target device. | | deviceId |string | Yes |ID of the target device. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
......
...@@ -26,16 +26,16 @@ Creates a **URLSearchParams** instance. ...@@ -26,16 +26,16 @@ Creates a **URLSearchParams** instance.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| init | string[][] \| Record&lt;string, string&gt; \| string \| URLSearchParams | No| Input parameter objects, which include the following:<br>- **string[][]**: two-dimensional string array<br>- **Record&lt;string, string&gt;**: list of objects<br>- **string**: string<br>- **URLSearchParams**: object | | init | string[][] \| Record&lt;string, string&gt; \| string \| URLSearchParams | No| Input parameter objects, which include the following:<br>- **string[][]**: two-dimensional string array<br>- **Record&lt;string, string&gt;**: list of objects<br>- **string**: string<br>- **URLSearchParams**: object|
**Example** **Example**
```js ```js
var objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); let objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
var objectParams1 = new Url.URLSearchParams({"fod" : 1 , "bard" : 2}); let objectParams1 = new Url.URLSearchParams({"fod" : '1' , "bard" : '2'});
var objectParams2 = new Url.URLSearchParams('?fod=1&bard=2'); let objectParams2 = new Url.URLSearchParams('?fod=1&bard=2');
var urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2');
var params = new Url.URLSearchParams(urlObject.search); let params = new Url.URLSearchParams(urlObject.search);
``` ```
...@@ -59,7 +59,7 @@ Appends a key-value pair into the query string. ...@@ -59,7 +59,7 @@ Appends a key-value pair into the query string.
```js ```js
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3); paramsObject.append('fod', '3');
``` ```
...@@ -109,10 +109,10 @@ Obtains all the key-value pairs based on the specified key. ...@@ -109,10 +109,10 @@ Obtains all the key-value pairs based on the specified key.
**Example** **Example**
```js ```js
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); let params = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3); // Add a second value for the fod parameter. params.append('fod', '3'); // Add a second value for the fod parameter.
console.log(params.getAll('fod')) // Output ["1","3"]. console.log(params.getAll('fod').toString()) // Output ["1","3"].
``` ```
...@@ -133,7 +133,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ...@@ -133,7 +133,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th
**Example** **Example**
```js ```js
var searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2"); let searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2");
for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs
console.log(pair[0]+ ', '+ pair[1]); console.log(pair[0]+ ', '+ pair[1]);
} }
...@@ -192,15 +192,14 @@ Obtains the value of the first key-value pair based on the specified key. ...@@ -192,15 +192,14 @@ Obtains the value of the first key-value pair based on the specified key.
| Type | Description | | Type | Description |
| -------- | -------- | | -------- | -------- |
| string | Returns the value of the first key-value pair if obtained. | | string | Returns the value of the first key-value pair if obtained. |
| null | Returns null if no value is obtained. | | null | Returns **null** if no value is obtained.|
**Example** **Example**
```js ```js
var paramsOject = new Url.URLSearchParams(document.location.search.substring(1)); let paramsObject = new Url.URLSearchParams('name=Jonathan&age=18');
var name = paramsOject.get("name"); // is the string "Jonathan" let name = paramsObject.get("name"); // is the string "Jonathan"
var age = parseInt(paramsOject.get("age"), 10); // is the number 18 let age = parseInt(paramsObject.get("age"), 10); // is the number 18
var address = paramsOject.get("address"); // null
``` ```
...@@ -253,7 +252,7 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t ...@@ -253,7 +252,7 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t
```js ```js
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.set('baz', 3); // Add a third parameter. paramsObject.set('baz', '3'); // Add a third parameter.
``` ```
...@@ -268,7 +267,7 @@ Sorts all key-value pairs contained in this object based on the Unicode code poi ...@@ -268,7 +267,7 @@ Sorts all key-value pairs contained in this object based on the Unicode code poi
**Example** **Example**
```js ```js
var searchParamsObject = new Url.URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object let searchParamsObject = new Url.URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object
searchParamsObject.sort(); // Sort the key/value pairs searchParamsObject.sort(); // Sort the key/value pairs
console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4
``` ```
...@@ -291,7 +290,7 @@ Obtains an ES6 iterator that contains the keys of all the key-value pairs. ...@@ -291,7 +290,7 @@ Obtains an ES6 iterator that contains the keys of all the key-value pairs.
**Example** **Example**
```js ```js
var searchParamsObject = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing let searchParamsObject = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
for (var key of searchParamsObject .keys()) { // Output key-value pairs for (var key of searchParamsObject .keys()) { // Output key-value pairs
console.log(key); console.log(key);
} }
...@@ -315,8 +314,8 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs. ...@@ -315,8 +314,8 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs.
**Example** **Example**
```js ```js
var searchParams = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing let searchParams = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
for (var value of searchParams.values()) { for (var value of searchParams.values()) {
console.log(value); console.log(value);
} }
``` ```
...@@ -340,7 +339,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ...@@ -340,7 +339,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th
```js ```js
const paramsObject = new Url.URLSearchParams('fod=bay&edg=bap'); const paramsObject = new Url.URLSearchParams('fod=bay&edg=bap');
for (const [name, value] of paramsObject) { for (const [name, value] of paramsObject) {
console.log(name, value); console.log(name, value);
} }
``` ```
...@@ -365,7 +364,7 @@ Obtains search parameters that are serialized as a string and, if necessary, per ...@@ -365,7 +364,7 @@ Obtains search parameters that are serialized as a string and, if necessary, per
```js ```js
let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new Url.URLSearchParams(url.search.slice(1)); let params = new Url.URLSearchParams(url.search.slice(1));
params.append('fod', 3); params.append('fod', '3');
console.log(params.toString()); console.log(params.toString());
``` ```
...@@ -405,16 +404,16 @@ Creates a URL. ...@@ -405,16 +404,16 @@ Creates a URL.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| url | string | Yes | Input object. | | url | string | Yes | Input object. |
| base | string \ |& URL | No | Input parameter, which can be any of the following:<br>- **string**: string<br>- **URL**: string or object | | base | string \| URL | No| Input parameter, which can be any of the following:<br>- **string**: string<br>- **URL**: string or object|
**Example** **Example**
```js ```js
var mm = 'http://username:password@host:8080'; let mm = 'http://username:password@host:8080';
var a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; let a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/';
var b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; let b = new Url.URL(mm); // Output 'http://username:password@host:8080/';
new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1';
var c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; let c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1';
new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1';
new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1';
new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1
...@@ -443,7 +442,7 @@ Converts the parsed URL into a string. ...@@ -443,7 +442,7 @@ Converts the parsed URL into a string.
```js ```js
const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
url.toString() url.toString();
``` ```
...@@ -464,5 +463,5 @@ Converts the parsed URL into a JSON string. ...@@ -464,5 +463,5 @@ Converts the parsed URL into a JSON string.
**Example** **Example**
```js ```js
const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
url.toJSON() url.toJSON();
``` ```
\ No newline at end of file
...@@ -141,7 +141,7 @@ Processes an asynchronous function and returns a promise version. ...@@ -141,7 +141,7 @@ Processes an asynchronous function and returns a promise version.
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| encoding | string | Yes| No| Encoding format.<br>- Supported formats: utf-8, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, x-mac-cyrilli, gbk, gb18030, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, utf-16be, utf-16le| | encoding | string | Yes| No| Encoding format.<br>- Supported formats: utf-8.|
| fatal | boolean | Yes| No| Whether to display fatal errors.| | fatal | boolean | Yes| No| Whether to display fatal errors.|
| ignoreBOM | boolean | Yes| No| Whether to ignore the byte order marker (BOM). The default value is **false**, which indicates that the result contains the BOM.| | ignoreBOM | boolean | Yes| No| Whether to ignore the byte order marker (BOM). The default value is **false**, which indicates that the result contains the BOM.|
......
# TextClock # TextClock
> ![](public_sys-resources/icon-note.gif) **NOTE** This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **<TextClock\>** component displays the current system time in text format for different time zones. The time is accurate to seconds. The **<TextClock\>** component displays the current system time in text format for different time zones. The time is accurate to seconds.
## Required Permissions >**NOTE**
>
None >This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components ## Child Components
None Not supported
## APIs ## APIs
TextClock(options?: {timeZoneOffset?: number, contorller?: TextClockController}) TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController })
- Parameters **Parameters**
| Name | Type| Mandatory| Default Value | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | ---- | ------------------ | ------------------------------------------------------------ | | -------------- | -------- | ------ | --------------------------------------------------------------------------- |
| timeZoneOffset | number | No | Time zone offset| Sets the time zone offset. The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8. For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region.| | timeZoneOffset | number | No | Time zone offset.<br>The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8.<br>For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region. If the set value is not within the valid range, the time zone offset of the current system will be used.<br/>Default value: time zone offset of the current system |
| contorller | [TextClockContorller](#TextClockController) | No| null | Binds a controller to control the status of the **<TextClock\>** component.| | controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **<TextClock\>** component. |
## Attributes ## Attributes
| Name | Type| Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| ------ | -------- | -------- | ------------------------------------------------------------ |
| format | string | 'hhmmss' | Time format, for example, **yyyy/mm/dd** or **yyyy-mm-dd**. Supported time format strings: <ul><li>yyyy (year)</li> <li>mm (two-letter abbreviated month name)</li> <li>mmm (three-letter abbreviated month name)</li> <li>mmmm (full month name)</li> <li>dd (two-letter abbreviated day of the week)</li> <li>ddd (three-letter abbreviated day of the week)</li> <li>dddd (full day of the week)</li> <li>HH (24-hour format)</li> <li>hh (12-hour format)</li> <li>MM/mm (minute)</li> <li>SS/ss (second)</li></ul>| | Name | Type | Description |
| ------ | --------------- | ------------------------------------------------------------ |
| format | string | Time format.<br>The date separator is a slash (/), and the time separator is a colon (:).<br>For example, yyyyMMdd and yyyy-MM-dd are displayed as yyyy/MM/dd,<br>and hhmmss is displayed as hh:mm:ss.<br>Only one digit is required for the time format. This means that hhmmss is equivalent to hms.<br>Supported time format strings:<br>- YYYY/yyyy: four-digit year<br>- YY/yy: last two digits of year<br>- M: one-digit month (MM for two-digit month, for example, 01)<br>- d: one-digit day (dd for two-digit day, for example, 01)<br>- D: number of days that have elapsed in the year<br>- H: 24-hour format<br>- h: 12-hour format<br>- m: minute<br>- s: second<br>- SSS: millisecond<br>Default value: **'hms'**|
## Events ## Events
In addition to the universal events (ts-universal-events-click.md), the following events are supported.
| Name | Description | | Name | Description |
| -------------------------------------------- | ------------------------------------------------------------ | | -------------------------------------------- | ------------------------------------------------------------ |
| onDateChange(event: (value: number) => void) | Triggered when the time changes in seconds at minimum.<br> **value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.| | onDateChange(event: (value: number) => void) | Called when the time changes in seconds at minimum.<br> - **value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.|
## TextClockController ## TextClockController
Controller of the **<TextClock\>** component, which can be bound to the component for status control. Defines the controller of the **<TextClock\>** component, which can be bound to the component for status control. A **\<TextClock>** component can be bound to only one controller.
### Objects to Import ### Objects to Import
``` ```ts
controller: TextClockController = new TextClockController() controller: TextClockController = new TextClockController()
``` ```
### start ### start
...@@ -61,7 +62,7 @@ Stops the **<TextClock\>** component. ...@@ -61,7 +62,7 @@ Stops the **<TextClock\>** component.
## Example ## Example
``` ```ts
@Entry @Entry
@Component @Component
struct Second { struct Second {
...@@ -69,26 +70,26 @@ struct Second { ...@@ -69,26 +70,26 @@ struct Second {
controller: TextClockController = new TextClockController() controller: TextClockController = new TextClockController()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center}) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('current milliseconds is' + this.accumulateTime) Text('Current milliseconds is ' + this.accumulateTime)
.fontSize(20) .fontSize(20)
TextClock({timeZoneOffset: -8, controller: this.controller}) TextClock({ timeZoneOffset: -8, controller: this.controller })
.format('hhmmss') .format('hms')
.onDateChange((value: number) => { .onDateChange((value: number) => {
this.accumulateTime = value this.accumulateTime = value
}) })
.margin(20) .margin(20)
.fontSize(30) .fontSize(30)
Button("start TextClock") Button("start TextClock")
.margin({ bottom: 10 }) .margin({ bottom: 10 })
.onClick(()=>{ .onClick(() => {
this.controller.start() this.controller.start()
}) })
Button("stop TextClock") Button("stop TextClock")
.onClick(()=>{ .onClick(() => {
this.controller.stop() this.controller.stop()
}) })
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
} }
......
...@@ -133,9 +133,8 @@ onStart() { ...@@ -133,9 +133,8 @@ onStart() {
context.requestPermissionsFromUser(array, 1, (err, data)=>{ context.requestPermissionsFromUser(array, 1, (err, data)=>{
console.info("====>requestdata====>" + JSON.stringify(data)); console.info("====>requestdata====>" + JSON.stringify(data));
console.info("====>requesterrcode====>" + JSON.stringify(err.code)); console.info("====>requesterrcode====>" + JSON.stringify(err.code));
} })
} }
``` ```
> **NOTE**<br> > **NOTE**<br>
> For details about how to use **requestPermissionsFromUser**, see [API Reference](../reference/apis/js-apis-ability-context.md). > For details about how to use **requestPermissionsFromUser**, see [API Reference](../reference/apis/js-apis-ability-context.md).
此差异已折叠。
...@@ -8,10 +8,10 @@ OpenHarmony系统传感器是应用访问底层硬件传感器的一种设备抽 ...@@ -8,10 +8,10 @@ OpenHarmony系统传感器是应用访问底层硬件传感器的一种设备抽
| 传感器类型 | 描述 | 说明 | 主要用途 | | 传感器类型 | 描述 | 说明 | 主要用途 |
| --------------------------------------- | --------- | ---------------------------------------- | -------------------- | | --------------------------------------- | --------- | ---------------------------------------- | -------------------- |
| SENSOR_TYPE_ACCELEROMETER | 加速度传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的加速度(包括重力加速度),单位&nbsp;:&nbsp;m/s2 | 检测运动状态 | | SENSOR_TYPE_ACCELEROMETER | 加速度传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的加速度(包括重力加速度),单位&nbsp;:&nbsp;m/s² | 检测运动状态 |
| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | 未校准加速度传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的未校准的加速度(包括重力加速度),单位&nbsp;:&nbsp;m/s2 | 检测加速度偏差估值 | | SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | 未校准加速度传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的未校准的加速度(包括重力加速度),单位&nbsp;:&nbsp;m/s² | 检测加速度偏差估值 |
| SENSOR_TYPE_LINEAR_ACCELERATION | 线性加速度传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的线性加速度(不包括重力加速度),单位&nbsp;:&nbsp;m/s2 | 检测每个单轴方向上的线性加速度 | | SENSOR_TYPE_LINEAR_ACCELERATION | 线性加速度传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的线性加速度(不包括重力加速度),单位&nbsp;:&nbsp;m/s² | 检测每个单轴方向上的线性加速度 |
| SENSOR_TYPE_GRAVITY | 重力传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的重力加速度,单位&nbsp;:&nbsp;m/s2 | 测量重力大小 | | SENSOR_TYPE_GRAVITY | 重力传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,施加在设备上的重力加速度,单位&nbsp;:&nbsp;m/s² | 测量重力大小 |
| SENSOR_TYPE_GYROSCOPE | 陀螺仪传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,设备的旋转角速度,单位&nbsp;:&nbsp;rad/s | 测量旋转的角速度 | | SENSOR_TYPE_GYROSCOPE | 陀螺仪传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,设备的旋转角速度,单位&nbsp;:&nbsp;rad/s | 测量旋转的角速度 |
| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | 未校准陀螺仪传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,设备的未校准旋转角速度,单位&nbsp;:&nbsp;rad/s | 测量旋转的角速度及偏差估值 | | SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | 未校准陀螺仪传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,设备的未校准旋转角速度,单位&nbsp;:&nbsp;rad/s | 测量旋转的角速度及偏差估值 |
| SENSOR_TYPE_SIGNIFICANT_MOTION | 大幅度动作传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,设备是否存在大幅度运动;如果取值为1则代表存在大幅度运动,取值为0则代表没有大幅度运动 | 用于检测设备是否存在大幅度运动 | | SENSOR_TYPE_SIGNIFICANT_MOTION | 大幅度动作传感器 | 测量三个物理轴(x、y&nbsp;&nbsp;z)上,设备是否存在大幅度运动;如果取值为1则代表存在大幅度运动,取值为0则代表没有大幅度运动 | 用于检测设备是否存在大幅度运动 |
...@@ -60,3 +60,4 @@ OpenHarmony传感器包含如下四个模块:Sensor API、Sensor Framework、S ...@@ -60,3 +60,4 @@ OpenHarmony传感器包含如下四个模块:Sensor API、Sensor Framework、S
| 心率计 | ohos.permission.READ_HEALTH_DATA | user_grant | 允许读取健康数据 | | 心率计 | ohos.permission.READ_HEALTH_DATA | user_grant | 允许读取健康数据 |
2. 传感器数据订阅和取消订阅接口成对调用,当不再需要订阅传感器数据时,开发者需要调用取消订阅接口停止数据上报。 2. 传感器数据订阅和取消订阅接口成对调用,当不再需要订阅传感器数据时,开发者需要调用取消订阅接口停止数据上报。
\ No newline at end of file
...@@ -23,7 +23,7 @@ Vibrator属于控制类小器件,主要包含以下四个模块:Vibrator API ...@@ -23,7 +23,7 @@ Vibrator属于控制类小器件,主要包含以下四个模块:Vibrator API
## 约束与限制 ## 约束与限制
在使用振动器时,开发者需要配置请求振动器的权限ohos.permission.VIBRATE,才能控制振动器振动,权限类型是system_grant 在使用振动器时,开发者需要配置请求振动器的权限ohos.permission.VIBRATE,才能控制振动器振动。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册