提交 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
## Available APIs
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
| 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.|
| 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. |
| 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. |
| 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. |
| 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**.|
| 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. |
| 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. |
| 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
The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module.
```js
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:
(2) Create a **KvManager** instance.
```js
import featureAbility from '@ohos.ability.featureAbility';
The sample code is as follows:
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.
The sample code is as follows:
```js
let kvManager;
try {
const kvManagerConfig = {
......@@ -64,12 +96,10 @@ The following uses a single KV store as an example to describe the development p
}
```
4. Create and obtain a single KV store.
3. Create and obtain a single KV store.
(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.
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:
```js
......@@ -100,7 +130,8 @@ The following uses a single KV store as an example to describe the development p
>
> 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.
4. Subscribe to changes in the distributed data.<br/>
5. Subscribe to changes in the distributed data.
The following is the sample code for subscribing to the data changes of a single KV store:
```js
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
});
```
5. Write data to the single KV store.
(1) Construct the key and value to be written into the single KV store.
6. Write data to the single KV store.
(2) Write key-value pairs 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.
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
}
```
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:
```js
......@@ -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.
> **NOTE**
......
......@@ -6,100 +6,98 @@ Applications save data to distributed databases by calling the DDS APIs. The DDS
You do not need to care about the implementation of the database locking mechanism.
## 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.
- **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.
- **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.
- **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.
- **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.
- **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.
- **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
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:
- **APIs**
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**
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 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 DDS consists of the following:
- **Storage component**
- **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.
The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution.
- **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.
- **Synchronization component**
- **Storage component**<br>The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution.
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**
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**<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.
- **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.
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>
**Figure 1** How DDS works
![](figures/en-us_image_0000001183386164.png)
## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
- 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 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
| 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.|
| 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.|
|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.|
### Managing Data in an RDB Store
......@@ -31,7 +31,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| 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**
......@@ -41,7 +41,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| 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**
......@@ -51,7 +51,7 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| 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**
......@@ -64,8 +64,8 @@ The **RDB** module provides APIs for inserting, deleting, updating, and querying
| 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 | 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 | 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.|
### Using Predicates
......@@ -77,11 +77,11 @@ The table below lists common predicates. For more information about predicates,
| 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 | 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 | 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 | 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 | 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 | 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
......@@ -97,12 +97,12 @@ For details about how to use result set APIs, see [Result Set](../reference/apis
| Class| API| Description|
| -------- | -------- | -------- |
| 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 | 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 | 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 | 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 | 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 | 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.|
......@@ -148,7 +148,7 @@ You can obtain the distributed table name for a remote device based on the local
| 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
......
......@@ -90,9 +90,9 @@ Use the following APIs to delete a **Storage** instance or data file.
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promise = dataStorage.getStorage(path + '/mystore');
});
```
......@@ -120,14 +120,15 @@ Use the following APIs to delete a **Storage** instance or data file.
```js
promise.then((storage) => {
let getPromise = storage.get('startup', 'default');
let getPromise = storage.get('startup', 'default')
getPromise.then((value) => {
console.info("The value of startup is " + value);
}).catch((err) => {
console.info("Failed to get the value of startup with err: " + err);
})
}).catch((err) => {
console.info("Failed to get the storage.");
console.info("Failed to get the storage.")
})
```
......@@ -149,7 +150,7 @@ Use the following APIs to delete a **Storage** instance or data file.
var observer = function (key) {
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.flushSync(); // Trigger the StorageObserver callback.
......@@ -169,7 +170,7 @@ Use the following APIs to delete a **Storage** instance or data file.
promise.then(() => {
console.info("Succeeded in deleting the storage.");
}).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 @@
| -------- | -------- | -------- |
| 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.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
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":[
{
"name":"ohos.permission.ACCELEROMETER",
"reason":"",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
{
"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"
}
},
]
```
- ohos.permission.GYROSCOPE
- ohos.permission.ACTIVITY_MOTION
- ohos.permission.READ_HEALTH_DATA
For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Subscribe to data changes of a type of sensor.
```
import sensor from "@ohos.sensor"
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){
console.info("Subscription succeeded. data = "+ data); // The call is successful, and the obtained sensor data is printed.
}
);
import sensor from "@ohos.sensor";
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data){
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**.
......@@ -87,11 +59,8 @@
3. Unsubscribe from sensor data changes.
```
import sensor from "@ohos.sensor"
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() {
console.info("Succeeded in unsubscribing from acceleration sensor data."); // The unsubscription is successful, and the result is printed.
}
);
import sensor from "@ohos.sensor";
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER);
```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
......@@ -101,11 +70,10 @@
4. Subscribe to only one data change of a type of sensor.
```
import sensor from "@ohos.sensor"
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed.
}
);
import sensor from "@ohos.sensor";
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
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**.
......@@ -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:
```
import sensor from "@ohos.sensor";
try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed.
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
} catch (error) {
console.error(error);
console.error("Failed to get sensor data");
}
```
\ No newline at end of file
......@@ -7,7 +7,7 @@ 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:
| 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_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 |
......@@ -21,9 +21,9 @@ A sensor is a device to detect events or changes in an environment and send mess
| 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_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_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_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_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_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 |
......@@ -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.
Table 7 Sensor data permissions
| 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.|
| 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. |
| 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.|
| 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.
\ No newline at end of file
......@@ -30,7 +30,7 @@ The following table lists the USB APIs currently available. For details, see the
## 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.
......
......@@ -10,65 +10,30 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
## Available APIs
| 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, 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.|
| 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, 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, 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, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. 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, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. This API uses a callback to return the result. |
## How to Develop
1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file.
```
"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"
}
},
]
```
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).
2. Trigger the device to vibrate.
```
import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error)=>{
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);
}else{ // The call is successful, and the device starts to vibrate.
Console.log("Promise returned to indicate a successful vibration.")
};
vibrator.vibrate(1000).then((error) => {
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);
} else { // The call is successful, and the device starts to vibrate.
console.log("Promise returned to indicate a successful vibration.")
}
})
```
......@@ -76,11 +41,11 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
```
import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{
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);
}else{ // The call is successful, and the device stops vibrating.
Console.log("Promise returned to indicate a successful stop.");
};
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => {
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);
} else { // The call is successful, and the device stops vibrating.
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
**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.
......@@ -23,4 +23,7 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
## 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
| 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.|
| version | number | Yes| RDB store version.|
| 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
**Example**
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call getRdbStore.
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) {
console.info("Failed to get RdbStore, err: " + err)
return
......@@ -59,7 +64,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
| 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.|
| 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
**Example**
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call getRdbStore.
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) => {
console.log("Got RdbStore successfully.")
}).catch((err) => {
......@@ -92,13 +102,18 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul
**Parameters**
| 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.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example**
```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) {
console.info("Failed to delete RdbStore, err: " + err)
return
......@@ -118,7 +133,7 @@ Deletes an RDB store. This API uses a promise to return the result.
**Parameters**
| 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.|
**Return value**
......@@ -128,7 +143,12 @@ Deletes an RDB store. This API uses a promise to return the result.
**Example**
```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(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
......@@ -166,7 +186,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
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
......@@ -191,7 +211,7 @@ predicates.inDevices(['12345678abcde'])
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
......@@ -780,14 +800,7 @@ Sets an **RdbPredicates** to filter out duplicate records.
**Example**
```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct("NAME")
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.")
})
predicates.equalTo("NAME", "Rose").distinct()
```
......@@ -1434,7 +1447,7 @@ try {
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
......@@ -1460,7 +1473,7 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) {
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
......
......@@ -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. |
| 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. |
| 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**
......@@ -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. |
| 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**
......@@ -444,7 +444,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore)
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -513,7 +513,7 @@ Subscribes to service status changes.
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -596,16 +596,15 @@ Enumerates the KV store types.
Enumerates the KV store security levels.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Value| Description |
| --- | ---- | ----------------------- |
| NO_LEVEL | 0 | No security level is set for the KV store. |
| S0 | 1 | The KV store security level is public.|
| 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.|
| 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.|
| 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.|
| 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.|
| 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.<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.<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.<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.<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.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
## Constants
......@@ -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). |
| 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**
......@@ -2159,7 +2158,7 @@ Deletes a KV pair from this KV store. This API uses an asynchronous callback to
| 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). |
| 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**
......@@ -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. |
| 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**
......@@ -2267,7 +2266,7 @@ Subscribes to synchronization complete events.
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -2328,7 +2327,7 @@ Inserts KV pairs in batches to this KV store. This API uses an asynchronous call
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -2430,7 +2429,7 @@ Deletes KV pairs in batches from this KV store. This API uses an asynchronous ca
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -2532,7 +2531,7 @@ Starts the transaction in this KV store. This API uses an asynchronous callback
| 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**
......@@ -2619,7 +2618,7 @@ Commits the transaction in this KV store. This API uses an asynchronous callback
| 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**
......@@ -2681,7 +2680,7 @@ Rolls back the transaction in this KV store. This API uses an asynchronous callb
| 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**
......@@ -2744,7 +2743,7 @@ Sets data synchronization, which can be enabled or disabled. This API uses an as
| 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. |
| 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**
......@@ -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. |
| 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**
......@@ -3141,7 +3140,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -3463,7 +3462,7 @@ Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -3635,7 +3634,7 @@ Deletes data of a device. This API uses an asynchronous callback to return the r
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -3824,7 +3823,7 @@ Sets the default delay allowed for KV store synchronization. This API uses an as
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -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. |
| 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**
......@@ -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. |
| 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**
......@@ -4146,7 +4145,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -4682,7 +4681,7 @@ Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......@@ -4961,7 +4960,7 @@ Deletes data of the specified device from this KV store. This API uses an asynch
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| 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**
......
......@@ -26,16 +26,16 @@ Creates a **URLSearchParams** instance.
| 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**
```js
var objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
var objectParams1 = new Url.URLSearchParams({"fod" : 1 , "bard" : 2});
var objectParams2 = new Url.URLSearchParams('?fod=1&bard=2');
var urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2');
var params = new Url.URLSearchParams(urlObject.search);
let objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
let objectParams1 = new Url.URLSearchParams({"fod" : '1' , "bard" : '2'});
let objectParams2 = new Url.URLSearchParams('?fod=1&bard=2');
let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2');
let params = new Url.URLSearchParams(urlObject.search);
```
......@@ -59,7 +59,7 @@ Appends a key-value pair into the query string.
```js
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3);
paramsObject.append('fod', '3');
```
......@@ -110,9 +110,9 @@ Obtains all the key-value pairs based on the specified key.
```js
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3); // Add a second value for the fod parameter.
console.log(params.getAll('fod')) // Output ["1","3"].
let params = new Url.URLSearchParams(urlObject.search.slice(1));
params.append('fod', '3'); // Add a second value for the fod parameter.
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
**Example**
```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
console.log(pair[0]+ ', '+ pair[1]);
}
......@@ -192,15 +192,14 @@ Obtains the value of the first key-value pair based on the specified key.
| Type | Description |
| -------- | -------- |
| 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**
```js
var paramsOject = new Url.URLSearchParams(document.location.search.substring(1));
var name = paramsOject.get("name"); // is the string "Jonathan"
var age = parseInt(paramsOject.get("age"), 10); // is the number 18
var address = paramsOject.get("address"); // null
let paramsObject = new Url.URLSearchParams('name=Jonathan&age=18');
let name = paramsObject.get("name"); // is the string "Jonathan"
let age = parseInt(paramsObject.get("age"), 10); // is the number 18
```
......@@ -253,7 +252,7 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t
```js
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
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
**Example**
```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
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.
**Example**
```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
console.log(key);
}
......@@ -315,7 +314,7 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs.
**Example**
```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()) {
console.log(value);
}
......@@ -365,7 +364,7 @@ Obtains search parameters that are serialized as a string and, if necessary, per
```js
let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new Url.URLSearchParams(url.search.slice(1));
params.append('fod', 3);
params.append('fod', '3');
console.log(params.toString());
```
......@@ -405,16 +404,16 @@ Creates a URL.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| 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**
```js
var mm = 'http://username:password@host:8080';
var a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/';
var b = new Url.URL(mm); // Output 'http://username:password@host:8080/';
let mm = 'http://username:password@host:8080';
let a = 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';
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', 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
......@@ -443,7 +442,7 @@ Converts the parsed URL into a string.
```js
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.
**Example**
```js
const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
url.toJSON()
url.toJSON();
```
......@@ -141,7 +141,7 @@ Processes an asynchronous function and returns a promise version.
| 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.|
| 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
> ![](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.
## Required Permissions
None
>**NOTE**
>
>This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
None
Not supported
## APIs
TextClock(options?: {timeZoneOffset?: number, contorller?: TextClockController})
TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController })
- Parameters
**Parameters**
| Name | Type| Mandatory| Default Value | 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.|
| contorller | [TextClockContorller](#TextClockController) | No| null | Binds a controller to control the status of the **<TextClock\>** component.|
| Name | Type | Mandatory | Description |
| -------------- | -------- | ------ | --------------------------------------------------------------------------- |
| 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 |
| controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **<TextClock\>** component. |
## Attributes
| Name | Type| Default Value | Description |
| ------ | -------- | -------- | ------------------------------------------------------------ |
| 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>|
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| 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
In addition to the universal events (ts-universal-events-click.md), the following events are supported.
| 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
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
```
```ts
controller: TextClockController = new TextClockController()
```
### start
......@@ -61,7 +62,7 @@ Stops the **<TextClock\>** component.
## Example
```
```ts
@Entry
@Component
struct Second {
......@@ -69,11 +70,11 @@ struct Second {
controller: TextClockController = new TextClockController()
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center}) {
Text('current milliseconds is' + this.accumulateTime)
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Current milliseconds is ' + this.accumulateTime)
.fontSize(20)
TextClock({timeZoneOffset: -8, controller: this.controller})
.format('hhmmss')
TextClock({ timeZoneOffset: -8, controller: this.controller })
.format('hms')
.onDateChange((value: number) => {
this.accumulateTime = value
})
......@@ -81,11 +82,11 @@ struct Second {
.fontSize(30)
Button("start TextClock")
.margin({ bottom: 10 })
.onClick(()=>{
.onClick(() => {
this.controller.start()
})
Button("stop TextClock")
.onClick(()=>{
.onClick(() => {
this.controller.stop()
})
}
......
# Matrix Transformation
> **NOTE**<br>
> **NOTE**
>
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
```ts
import matrix4 from '@ohos.matrix4'
```
......@@ -23,7 +23,7 @@ None
init(array: Array&lt;number&gt;): Object
Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used.
Implements a 4x4 matrix by using the input parameter. The column-major order is used.
- Parameters
......@@ -39,29 +39,29 @@ Matrix constructor, which is used to create a 4x4 matrix by using the input para
- Parameter description
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| m00 | number | Yes | Scaling value of the x-axis. Defaults to **1** for the unit matrix. |
| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. |
| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. |
| m00 | number | Yes | Scaling value along the x-axis. Defaults to **1** for the identity matrix. |
| m01 | number | Yes | The second value, which is affected by the rotation along the x, y, and z axes. |
| m02 | number | Yes | The third value, which is affected by the rotation along the x, y, and z axes. |
| m03 | number | Yes | Meaningless. |
| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. |
| m11 | number | Yes | Scaling value of the y-axis. Defaults to **1** for the unit matrix. |
| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. |
| m10 | number | Yes | The fifth value, which is affected by the rotation along the x, y, and z axes. |
| m11 | number | Yes | Scaling value along the y-axis. Defaults to **1** for the identity matrix. |
| m12 | number | Yes | The seventh value, which is affected by the rotation along the x, y, and z axes. |
| m13 | number | Yes | Meaningless. |
| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. |
| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. |
| m22 | number | Yes | Scaling value of the z-axis. Defaults to **1** for the unit matrix. |
| m20 | number | Yes | The ninth value, which is affected by the rotation along the x, y, and z axes. |
| m21 | number | Yes | The tenth value, which is affected by the rotation along the x, y, and z axes. |
| m22 | number | Yes | Scaling value along the z-axis. Defaults to **1** for the identity matrix. |
| m23 | number | Yes | Meaningless. |
| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the unit matrix. |
| m31 | number | Yes | Translation value of the y-axis, in px. Defaults to **0** for the unit matrix. |
| m32 | number | Yes | Translation value of the z-axis, in px. Defaults to **0** for the unit matrix. |
| m30 | number | Yes | Translation value along the x-axis, in px. Defaults to **0** for the identity matrix. |
| m31 | number | Yes | Translation value along the y-axis, in px. Defaults to **0** for the identity matrix. |
| m32 | number | Yes | Translation value along the z-axis, in px. Defaults to **0** for the identity matrix. |
| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. |
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
// Create a 4x4 matrix.
let matrix = Matrix4.init([1.0, 0.0, 0.0, 0.0,
let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0])
......@@ -73,20 +73,20 @@ Matrix constructor, which is used to create a 4x4 matrix by using the input para
identity(): Object
Matrix initialization function. Can return a unit matrix object.
Performs matrix initialization. This API returns an identity matrix object.
- Return value
| Type | Description |
| -------- | -------- |
| Object | Unit matrix object. |
| Object | Identity matrix object. |
- Example
```
```ts
// The effect of matrix 1 is the same as that of matrix 2.
import Matrix4 from '@ohos.matrix4'
let matrix = Matrix4.init([1.0, 0.0, 0.0, 0.0,
import matrix4 from '@ohos.matrix4'
let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0])
......@@ -99,22 +99,22 @@ Matrix initialization function. Can return a unit matrix object.
copy(): Object
Matrix copy function, which is used to copy the current matrix object.
Copies this matrix object.
- Return value
| Type | Description |
| -------- | -------- |
| Object | Copy object of the current matrix. |
| Object | Copy of the current matrix object. |
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
@Entry
@Component
struct Test {
private matrix1 = Matrix4.identity().translate({x:100})
private matrix1 = matrix4.identity().translate({x:100})
private matrix2 = this.matrix1.copy().scale({x:2})
build() {
Column() {
......@@ -143,28 +143,28 @@ Matrix copy function, which is used to copy the current matrix object.
combine(matrix: Matrix4): Object
Matrix overlay function, which is used to overlay the effects of two matrices to generate a new matrix object.
Combines this matrix object with another to generate a new matrix object.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| matrix | Matrix4 | Yes | - | Matrix object to be overlaid. |
| matrix | Matrix4 | Yes | - | Matrix object to combine. |
- Return value
| Type | Description |
| -------- | -------- |
| Object | Object after matrix overlay. |
| Object | Object after the combination. |
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
@Entry
@Component
struct Test {
private matrix1 = Matrix4.identity().translate({x:200}).copy()
private matrix2 = Matrix4.identity().scale({x:2}).copy()
private matrix1 = matrix4.identity().translate({x:200}).copy()
private matrix2 = matrix4.identity().scale({x:2}).copy()
build() {
Column() {
// Translate the x-axis by 100 pixels and then scale it up or down by 2x.
......@@ -185,7 +185,7 @@ Matrix overlay function, which is used to overlay the effects of two matrices to
invert(): Object
Matrix inverse function. Can return an inverse matrix of the current matrix object, that is, get an opposite effect.
Inverts this matrix object.
- Return value
......@@ -195,11 +195,11 @@ Matrix inverse function. Can return an inverse matrix of the current matrix obje
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x).
let matrix1 = Matrix4.identity().scale({x:2})
let matrix2 = matrix1.invert()
let matrix1 = matrix4.identity().scale({x:2})
let matrix2 = matrix1.copy().invert()
```
......@@ -208,15 +208,15 @@ Matrix inverse function. Can return an inverse matrix of the current matrix obje
translate({x?: number, y?: number, z?: number}): Object
Matrix translation function, which is used to add the translation effect to the x, y, and z axes of the current matrix.
Translates this matrix object along the x, y, and z axes.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x | number | No | 0 | Translation distance of the x-axis, in px. |
| y | number | No | 0 | Translation distance of the y-axis, in px. |
| z | number | No | 0 | Translation distance of the z-axis, in px. |
| x | number | No | 0 | Translation distance along the x-axis, in px. |
| y | number | No | 0 | Translation distance along the y-axis, in px. |
| z | number | No | 0 | Translation distance along the z-axis, in px. |
- Return value
......@@ -226,12 +226,12 @@ Matrix translation function, which is used to add the translation effect to the
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
@Entry
@Component
struct Test {
private matrix1 = Matrix4.identity().translate({x:100, y:200, z:30})
private matrix1 = matrix4.identity().translate({x:100, y:200, z:30})
build() {
Column() {
Image($r("app.media.bg1")).transform(this.matrix1)
......@@ -250,15 +250,15 @@ Matrix translation function, which is used to add the translation effect to the
scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Object
Matrix scaling function, which is used to add the scaling effect to the x, y, and z axes of the current matrix.
Scales this matrix object along the x, y, and z axes.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x | number | No | 1 | Scaling multiple of the x-axis. |
| y | number | No | 1 | Scaling multiple of the y-axis. |
| z | number | No | 1 | Scaling multiple of the z-axis. |
| x | number | No | 1 | Scaling multiple along the x-axis. |
| y | number | No | 1 | Scaling multiple along the y-axis. |
| z | number | No | 1 | Scaling multiple along the z-axis. |
| centerX | number | No | 0 | X coordinate of the center point. |
| centerY | number | No | 0 | Y coordinate of the center point. |
......@@ -270,12 +270,12 @@ Matrix scaling function, which is used to add the scaling effect to the x, y, an
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
@Entry
@Component
struct Test {
private matrix1 = Matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50})
private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50})
build() {
Column() {
Image($r("app.media.bg1")).transform(this.matrix1)
......@@ -294,7 +294,7 @@ Matrix scaling function, which is used to add the scaling effect to the x, y, an
rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Object
Matrix rotation function, which is used to add the rotation effect to the x, y, and z axes of the current matrix.
Rotates this matrix object along x, y, and z axes.
- Parameters
......@@ -315,12 +315,12 @@ Matrix rotation function, which is used to add the rotation effect to the x, y,
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
@Entry
@Component
struct Test {
private matrix1 = Matrix4.identity().rotate({x:1, y:1, z:2, angle:30})
private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30})
build() {
Column() {
Image($r("app.media.bg1")).transform(this.matrix1)
......@@ -339,7 +339,7 @@ Matrix rotation function, which is used to add the rotation effect to the x, y,
transformPoint(point: Point): Point
Matrix point transformation function, which is used to apply the current transformation effect to a coordinate point.
Applies this transformation effect to a coordinate point.
- Parameters
......@@ -355,14 +355,14 @@ Matrix point transformation function, which is used to apply the current transfo
- Example
```
import Matrix4 from '@ohos.matrix4'
```ts
import matrix4 from '@ohos.matrix4'
import prompt from '@system.prompt'
@Entry
@Component
struct Test {
private matrix1 = Matrix4.identity().transformPoint([100, 10])
private matrix1 = matrix4.identity().transformPoint([100, 10])
build() {
Column() {
Button("get Point")
......
......@@ -133,9 +133,8 @@ onStart() {
context.requestPermissionsFromUser(array, 1, (err, data)=>{
console.info("====>requestdata====>" + JSON.stringify(data));
console.info("====>requesterrcode====>" + JSON.stringify(err.code));
}
})
}
```
> **NOTE**<br>
> For details about how to use **requestPermissionsFromUser**, see [API Reference](../reference/apis/js-apis-ability-context.md).
......@@ -19,6 +19,7 @@
- Declarative UI Description Specifications
- [Configuration Without Parameters](ts-parameterless-configuration.md)
- [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md)
- [Attribute Configuration](ts-attribution-configuration.md)
- [Event Configuration](ts-event-configuration.md)
- [Child Component Configuration](ts-child-component-configuration.md)
......@@ -70,6 +71,8 @@
- [Building a Food Category List Layout](ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
- [Recommendations for Improving Performance](ts-performance-improvement-recommendation.md)
- JavaScript-based Web-like Development Paradigm
- [Overview](ui-js-overview.md)
- Framework
......
......@@ -26,58 +26,30 @@
| -------- | -------- | -------- |
| ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | 持续监听传感器数据变化 |
| ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | 获取一次传感器数据变化 |
| ohos.sensor | sensor.off(sensorType, callback:AsyncCallback&lt;void&gt;): void | 注销传感器数据的监听 |
| ohos.sensor | sensor.off(sensorType, callback?:AsyncCallback&lt;void&gt;): void | 注销传感器数据的监听 |
## 开发步骤
1. 获取设备上传感器的数据,需要在“config.json”里面进行配置请求权限。具体如下:
1. 获取设备上传感器的数据前,需要检查是否已经配置请求相应的权限。 <br>
系统提供的传感器权限有:
- ohos.permission.ACCELEROMETER
```
"reqPermissions":[
{
"name":"ohos.permission.ACCELEROMETER",
"reason":"",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
{
"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"
}
},
]
```
- ohos.permission.GYROSCOPE
- ohos.permission.ACTIVITY_MOTION
- ohos.permission.READ_HEALTH_DATA
具体配置方式请参考[权限申请声明](../security/accesstoken-guidelines.md)
2. 持续监听传感器数据变化。
```
import sensor from "@ohos.sensor"
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){
console.info("Subscription succeeded. data = " + data);//调用成功,打印对应传感器的数据
}
);
import sensor from "@ohos.sensor";
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data){
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z);// 获取数据成功
});
```
以SensorType为SENSOR_TYPE_ID_ACCELEROMETER为例展示运行结果,持续监听传感器接口的结果如下图所示:
......@@ -87,11 +59,8 @@
3. 注销传感器数据监听。
```
import sensor from "@ohos.sensor"
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() {
console.info("Succeeded in unsubscribing from acceleration sensor data.");//注销成功,返回打印结果
}
);
import sensor from "@ohos.sensor";
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER);
```
以SensorType为SENSOR_TYPE_ID_ACCELEROMETER为例展示运行结果,注销传感器成功结果如下图所示:
......@@ -101,11 +70,10 @@
4. 获取一次传感器数据变化。
```
import sensor from "@ohos.sensor"
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
console.info("Data obtained successfully. data=" + data);//获取数据成功,打印对应传感器的数据
}
);
import sensor from "@ohos.sensor";
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z);// 获取数据成功
});
```
以SensorType为SENSOR_TYPE_ID_ACCELEROMETER为例展示运行结果,获取数据成功日志如下图所示:
......@@ -115,15 +83,15 @@
若接口调用不成功,建议使用try/catch语句捕获代码中可能出现的错误信息。例如:
```
import sensor from "@ohos.sensor";
try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
console.info("Data obtained successfully. data=" + data);//获取数据成功,打印对应传感器的数据
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z);// 获取数据成功
});
} catch (error) {
console.error(error);
console.error("Get sensor data fail");
}
```
## 相关实例
针对传感器开发,有以下相关实例可供参考:
......
......@@ -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.
先完成此消息的编辑!
想要评论请 注册