diff --git a/README_zh.md b/README_zh.md index 651d0ddcb30683c6e8e239a67e5e90c90dae81f9..0add1ca75ee7fb41dd56d1a180b3abf30098ea76 100644 --- a/README_zh.md +++ b/README_zh.md @@ -20,7 +20,7 @@ master:最新开发版本。 发布OpenHarmony 3.1 Beta版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.1-beta.md)。 -发布OpenHarmony 3.0 LTS版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)。该版本已更新至OpenHarmony 3.0.1 LTS,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.0.1-LTS.md)。 +发布OpenHarmony 3.0 LTS版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)。该版本已更新至OpenHarmony 3.0.2 LTS,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md)。 发布 OpenHarmony v2.2 Beta2版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)。 diff --git a/en/application-dev/database/Readme-EN.md b/en/application-dev/database/Readme-EN.md index 2555d715a720db4389f502176f9c84226717fcce..6184dc593c212732af684fdecbcde73156be82b0 100644 --- a/en/application-dev/database/Readme-EN.md +++ b/en/application-dev/database/Readme-EN.md @@ -7,5 +7,9 @@ - [RDB Overview](database-relational-overview.md) - [RDB Development](database-relational-guidelines.md) - Lightweight Data Store - - [Lightweight Data Store Overview](database-preference-overview.md) - - [Lightweight Data Store Development](database-preference-guidelines.md) \ No newline at end of file + - [Lightweight Data Store Overview](database-distributedobject-overview.md) + - [Lightweight Data Store Development](database-distributedobject-guidelines.md) + + + + \ No newline at end of file diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 2411dd2c9a15ce0976587dd3caa74e31e7777ce5..494ebd562b0cf6c241137823e2360122c21f5bea 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -1,671 +1,316 @@ -# RDB Development +# RDB Development -## When to Use +## When to Use -On the basis of the SQLite database, the RDB allows you to operate data with or without native SQL statements. An RDB is also called RDB store. +On the basis of the SQLite database, the relational database (RDB) allows you to operate data with or without native SQL statements. In OpenHarmony, an RDB is also called RDB store. -## Available APIs + +## Available APIs **Creating and Deleting an RDB Store** -The following table describes APIs available for creating and deleting an RDB store. - -**Table 1** APIs for creating and deleting an RDB store - - - - - - - - - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

dataRdb

-

getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void

-

Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a callback to return the result.

-
  • config: configuration of the RDB store.
  • version: version of the RDB store.
  • callback: callback invoked to return the RDB store.
-

dataRdb

-

getRdbStore(config: StoreConfig, version: number): Promise<RdbStore>

-

Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a promise to return the result.

-
  • config: configuration of the RDB store.
  • version: version of the RDB store.
-

dataRdb

-

deleteRdbStore(name: string, callback: AsyncCallback<void>): void

-

Deletes an RDB store. This method uses a callback to return the result.

-
  • name: name of the RDB store to delete.
  • callback: callback invoked to return the result. If the RDB store is deleted, true will be returned. Otherwise, false will be returned.
-

dataRdb

-

deleteRdbStore(name: string): Promise<void>

-

Deletes an RDB store. This method uses a promise to return the result.

-
  • name: name of the RDB store to delete.
-
+The following table describes the APIs available for creating and deleting an RDB store. -**Managing Data in an RDB Store** +**Table 1** APIs for creating and deleting an RDB store + +| Class| API| Description| +| -------- | -------- | -------- | +| dataRdb | getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | Obtains an RDB store. This method uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| +| dataRdb | getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.| +| dataRdb | deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result. If the RDB store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +| dataRdb | deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| -The RDB provides APIs for inserting, deleting, modifying, and querying data in the local RDB store. - -- **Inserting data** - - The RDB provides methods for inserting data through **ValuesBucket** in a data table. If the data is inserted successfully, the row number of the data inserted is returned; otherwise, **-1** is returned. - - **Table 2** APIs for inserting data to a data table - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

RdbStore

-

insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void

-

Inserts a row of data into a table. This method uses a callback to return the result.

-
  • name: name of the target table.
  • values: data to be inserted into the table.
  • callback: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, -1 will be returned.
-

RdbStore

-

insert(name: string, values: ValuesBucket): Promise<number>

-

Inserts a row of data into a table. This method uses a promise to return the result.

-
  • name: name of the target table.
  • values: data to be inserted into the table.
-
- -- **Updating data** - - Call the **update\(\)** method to pass the new data and specify the update conditions by using **RdbPredicates**. If the data is successfully updated, the row number of the updated data is returned; otherwise, **0** is returned. - - **Table 3** APIs for updating data - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

RdbStore

-

update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void

-

Updates the data that meets the conditions specified by the RdbPredicates object. This method uses a callback to return the result.

-
  • values: data to update, which is stored in ValuesBucket.
  • rdbPredicates: conditions for updating data.
  • callback: callback invoked to return the number of rows updated.
-

RdbStore

-

update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise

-

Updates the data that meets the conditions specified by the RdbPredicates object. This method uses a promise to return the result.

-
  • values: data to update, which is stored in ValuesBucket.
  • rdbPredicates: conditions for updating data.
-
- -- **Deleting data** - - Call the **delete\(\)** method to delete data meeting the conditions specified by **RdbPredicates**. If the data is deleted, the row number of the deleted data is returned; otherwise, **0** is returned. - - **Table 4** APIs for deleting data - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

RdbStore

-

delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void

-

Deletes data based on the conditions specified by RdbPredicates. This method uses a callback to return the result.

-
  • rdbPredicates: conditions for deleting data.
  • callback: callback invoked to return the number of rows deleted.
-

RdbStore

-

delete(rdbPredicates: RdbPredicates): Promise

-

Deletes data based on the conditions specified by RdbPredicates. This method uses a promise to return the result.

-
  • rdbPredicates: conditions for deleting data.
-
- -- **Querying data** - - You can query data in the RDB in either of the following ways: - - - Call the **query** method to query data based on the predicates, without passing any SQL statement. - - Run the native SQL statement. - - **Table 5** APIs for querying data - - - - - - - - - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

RdbStore

-

query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void;

-

Queries data in the database based on specified conditions. This method uses a callback to return the result.

-
  • rdbPredicates: conditions for querying data.
-
  • columns: columns to query. If this parameter is not specified, the query applies to all columns.
  • callback: callback invoked to return the result. If the operation is successful, a ResultSet object will be returned.
-

RdbStore

-

query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet>;

-

Queries data in the database based on specified conditions. This method uses a promise to return the result.

-
  • rdbPredicates: conditions for querying data.
-
  • columns: columns to query. If this parameter is not specified, the query applies to all columns.
-

RdbStore

-

querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void

-

Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.

-
  • sql: SQL statement.
-
  • bindArgs: arguments in the SQL statement.
  • callback: callback invoked to return the result. If the operation is successful, a ResultSet object will be returned.
-

RdbStore

-

querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet>

-

Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.

-
  • sql: SQL statement.
-
  • bindArgs: arguments in the SQL statement.
-
+**Managing Data in an RDB Store** +The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. + +- **Inserting data** + The RDB provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. + **Table 2** APIs for inserting data + + | Class| API| Description| + | -------- | -------- | -------- | + | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This method uses a callback to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + | RdbStore | insert(name: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This method uses a promise to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.| + +- **Updating data** + Call the **update()** method to pass new data and specify the update conditions by using **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. + + **Table 3** APIs for updating data + + | Class| API| Description| + | -------- | -------- | -------- | + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.| + +- **Deleting data** + Call the **delete()** method to delete data meeting the conditions specified by **RdbPredicates**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. + + **Table 4** APIs for deleting data + + | Class| API| Description| + | -------- | -------- | -------- | + | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows deleted.| + | RdbStore | delete(rdbPredicates: RdbPredicates): Promise | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for deleting data.| + +- **Querying data** + You can query data in an RDB store in either of the following ways: + + - Call the **query()** method to query data based on the predicates, without passing any SQL statement. + - Run the native SQL statement. + + **Table 5** APIs for querying data + + | Class| API| Description| + | -------- | -------- | -------- | + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| **Using Predicates** -The RDB provides **RdbPredicates** for you to set database operation conditions. - -**Table 6** APIs for RDB predicates - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

RdbPredicates

-

equalTo(field: string, value: ValueType): RdbPredicates

-

Sets the RdbPredicates to match the field with data type ValueType and value equal to the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

notEqualTo(field: string, value: ValueType): RdbPredicates

-

Sets the RdbPredicates to match the field with data type ValueType and value not equal to the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

beginWrap(): RdbPredicates

-

Adds a left parenthesis to the RdbPredicates.

-
  • RdbPredicates: RdbPredicates with a left parenthesis.
-

RdbPredicates

-

endWrap(): RdbPredicates

-

Adds a right parenthesis to the RdbPredicates.

-
  • RdbPredicates: RdbPredicates with a right parenthesis.
-

RdbPredicates

-

or(): RdbPredicates

-

Adds the OR condition to the RdbPredicates.

-
  • RdbPredicates: RdbPredicates with the OR condition.
-

RdbPredicates

-

and(): RdbPredicates

-

Adds the AND condition to the RdbPredicates.

-
  • RdbPredicates: RdbPredicates with the AND condition.
-

RdbPredicates

-

contains(field: string, value: string): RdbPredicats

-

Sets the RdbPredicates to match a string containing the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

beginsWith(field: string, value: string): RdbPredicates

-

Sets the RdbPredicates to match a string that starts with the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

endsWith(field: string, value: string): RdbPredicates

-

Sets the RdbPredicates to match a string that ends with the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

isNull(field: string): RdbPredicates

-

Sets the RdbPredicates to match the field whose value is null.

-
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

isNotNull(field: string): RdbPredicates

-

Sets the RdbPredicates to match the field whose value is not null.

-
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

like(field: string, value: string): RdbPredicates

-

Sets the RdbPredicates to match a string that is similar to the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

glob(field: string, value: string): RdbPredicates

-

Sets the RdbPredicates to match the specified string.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

between(field: string, low: ValueType, high: ValueType): RdbPredicates

-

Sets the RdbPredicates to match the field with data type ValueType and value within the specified range.

-
  • field: column name in the database table.
  • low: minimum value that matches the RdbPredicates.
  • high: maximum value that matches the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates

-

Sets the RdbPredicates to match the field with data type ValueType and value out of the specified range.

-
  • field: column name in the database table.
  • low: minimum value that matches the RdbPredicates.
  • high: maximum value that matches the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

greaterThan(field: string, value: ValueType): RdbPredicatesgr

-

Sets the RdbPredicates to match the field with data type ValueType and value greater than the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

lessThan(field: string, value: ValueType): RdbPredicates

-

Sets the RdbPredicates to match the field with data type ValueType and value less than the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates

-

Sets the RdbPredicates to match the field with data type ValueType and value greater than or equal to the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates

-

Sets the RdbPredicates to match the field with data type ValueType and value less than or equal to the specified value.

-
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

orderByAsc(field: string): RdbPredicates

-

Sets the RdbPredicates to match the column with values sorted in ascending order.

-
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

orderByDesc(field: string): RdbPredicates

-

Sets the RdbPredicates to match the column with values sorted in descending order.

-
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

distinct(): RdbPredicates

-

Sets the RdbPredicates to filter out duplicate records.

-
  • RdbPredicates: RdbPredicates that can filter out duplicate records.
-

RdbPredicates

-

limitAs(value: number): RdbPredicates

-

Sets the RdbPredicates to specify the maximum number of records to match in a column.

-
  • value: maximum number of records in a column.
  • RdbPredicates: RdbPredicates that can be used to set the maximum number of records to match in a column.
-

RdbPredicates

-

offsetAs(rowOffset: number): RdbPredicates

-

Sets the RdbPredicates to specify the start position of the returned result.

-
  • rowOffset: start position of the returned result. The value is a positive integer.
  • RdbPredicates: RdbPredicates object that specifies the start position of the returned result.
-

RdbPredicates

-

groupBy(fields: Array<string>): RdbPredicates

-

Sets the RdbPredicates to group rows that have the same value into summary rows.

-
  • fields: names of the columns grouped for querying data.
  • RdbPredicates: RdbPredicates that groups rows that have the same value.
-

RdbPredicates

-

indexedBy(indexName: string): RdbPredicates

-

Sets the RdbPredicates object to specify the index column.

-
  • indexName: name of the index column.
  • RdbPredicates: RdbPredicates object that specifies the index column.
-

RdbPredicates

-

in(field: string, value: Array<ValueType>): RdbPredicates

-

Sets the RdbPredicates to match the field with data type Array<ValueType> and value within the specified range.

-
  • field: column name in the database table.
-
  • value: array of ValueType to match.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-

RdbPredicates

-

notIn(field: string, value: Array<ValueType>): RdbPredicates

-

Sets the RdbPredicates to match the field with data type Array<ValueType> and value out of the specified range.

-
  • field: column name in the database table.
-
  • value: array of ValueType to match.
  • RdbPredicates: RdbPredicates object that matches the specified field.
-
+The RDB provides **RdbPredicates** for you to set database operation conditions. + +**Table 6** APIs for using RDB store predicates + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbPredicates |inDevices(devices: Array): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis. | +| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis. | +| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition. | +| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition. | +| RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string. | +| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string. | +| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string. | +| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string. | +| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string. | +| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that sorts the values in ascending order. | +| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that sorts the values in descending order. | +| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records. | +| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records. | +| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result. | +| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value. | +| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column. | +| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | +| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field. | **Using the Result Set** -A result set can be regarded as rows of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. - ->![](public_sys-resources/icon-notice.gif) **NOTICE:** ->After a result set is used, you must call the **close\(\)** method to close it explicitly. - -**Table 7** APIs for using the result set - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

ResultSet

-

goTo(offset:number): boolean

-

Moves the result set forwards or backwards by an offset relative to its current position.

-

ResultSet

-

goToRow(position: number): boolean

-

Moves the result set to a specified row.

-

ResultSet

-

goToNextRow(): boolean

-

Moves the result set to the next row.

-

ResultSet

-

goToPreviousRow(): boolean

-

Moves the result set to the previous row.

-

ResultSet

-

getColumnIndex(columnName: string): number

-

Obtains the column index based on the specified column name.

-

ResultSet

-

getColumnName(columnIndex: number): string

-

Obtains the column name based on the specified column index.

-

ResultSet

-

goToFirstRow(): boolean

-

Checks whether the result set is located in the first row.

-

ResultSet

-

goToLastRow(): boolean

-

Checks whether the result set is located in the last row.

-

ResultSet

-

getString(columnIndex: number): string

-

Obtains the values in the specified column of the current row, in strings.

-

ResultSet

-

getBlob(columnIndex: number): Uint8Array

-

Obtains the values in the specified column of the current row, in a byte array.

-

ResultSet

-

getDouble(columnIndex: number): number

-

Obtains the values in the specified column of the current row, in double.

-

ResultSet

-

isColumnNull(columnIndex: number): boolean

-

Checks whether the values in the specified column of the current row are null.

-

ResultSet

-

close(): void

-

Closes the result set.

-
- -**Encrypting an RDB Store** +A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. + +> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE** +> After a result set is used, you must call the **close()** method to close it explicitly. + +**Table 7** APIs for using the result set + +| Class| API| Description| +| -------- | -------- | -------- | +| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| +| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| +| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| +| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| +| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| +| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| +| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| +| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| +| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| +| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| +| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| +| ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| +| ResultSet | close(): void | Closes the result set.| + +**Changing the Encryption Key for an RDB Store** You can encrypt an RDB store. When creating an RDB store, you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key. You can change the key but cannot delete it. -Once an RDB store is created without a key, you cannot add a key any longer. - -**Table 8** APIs for changing the key - - - - - - - - - - - - - - - - -

Class

-

API

-

Description

-

RdbStore

-

changeEncryptKey(newEncryptKey:Uint8Array, callback: AsyncCallback<number>):void;

-

Changes the encryption key for an RDB store. This method uses a callback to return the result. If the key is changed, 0 is returned. Otherwise, a non-zero value is returned.

-

RdbStore

-

changeEncryptKey(newEncryptKey:Uint8Array): Promise<number>;

-

Changes the encryption key for an RDB store. This method uses a promise to return the result. If the key is changed, 0 is returned. Otherwise, a non-zero value is returned.

-
- -## How to Develop - -1. Create an RDB store. - - 1. Configure the RDB attributes, including the name and storage mode of the database and whether it is read-only. - 2. Initialize the table structure and related data in the database. - 3. Create an RDB store. +Once an RDB store is created without a key, you can no longer add a key for it. - The sample code is as follows: +**Table 8** APIs for changing the encryption key - ``` - import dataRdb from '@ohos.data.rdb'; - - const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIG = {name: "rdbstore.db",} - - let rdbStore = await dataRdb.getRdbStore(STORE_CONFIG, 1); - await rdbStore.executeSql(CREATE_TABLE_TEST); - ``` +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore | changeEncryptKey(newEncryptKey:Uint8Array, callback: AsyncCallback<number>):void; | Changes the encryption key for this RDB store. This method uses a callback to return the result. If the operation is successful, **0** will be returned. Otherwise, a non-zero value will be returned.| +| RdbStore | changeEncryptKey(newEncryptKey:Uint8Array): Promise<number>; | Changes the encryption key for this RDB store. This method uses a promise to return the result. If the operation is successful, **0** will be returned. Otherwise, a non-zero value will be returned.| + +**Setting Distributed Tables** + +You can set a list of distributed tables for data operations across devices. + +**Table 9** APIs for setting distributed tables + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore | setDistributedTables(tables: Array, callback: AsyncCallback): void;| Sets a list of distributed tables. This method uses a callback to return the result.
-  **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| +| RdbStore | setDistributedTables(tables: Array): Promise; | Sets a list of distributed tables. This method uses a promise to return the result.
-  **tables**: names of the distributed tables to set.| + +**Obtaining the Distributed Table Name for a Remote Device** + +You can obtain the distributed table name for a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device. + +**Table 10** API for obtaining the distributed table name of a remote device + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback): void; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a callback to return the result.
- **device**: remote device.
-  **table**: local table name.
-  **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a promise to return the result.
- **device**: remote device.
-  **table**: local table name.| + +**Synchronizing Data Between Devices** + +**Table 11** APIs for synchronizing data between devices + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback>): void;| Synchronizes data between devices. This method uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise>;| Synchronizes data between devices. This method uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | + + +**Registering an RDB Store Observer** -2. Insert data. +**Table 12** API for registering an observer - 1. Create a **ValuesBucket** object to store the data you need to insert. - 2. Call the **insert\(\)** method to insert data into the RDB store. +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback>): void;| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| + +**Unregistering an RDB Store Observer** + +**Table 13** API for unregistering an observer + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback>): void;| Unregisters the observer of the specified type for the RDB store. This method uses a callback to return the result.
-  **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
-  **observer**: observer to unregister.| + + +## How to Develop + +1. Create an RDB store. + 1. Configure the RDB store attributes, including the RDB store name, storage mode, and whether read-only mode is used. + 2. Initialize the table structure and related data in the RDB store. + 3. Create the RDB store. + + The sample code is as follows: + + ``` + import dataRdb from '@ohos.data.rdb'; + + const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + const STORE_CONFIG = {name: "rdbstore.db",} + + let rdbStore = await dataRdb.getRdbStore(STORE_CONFIG, 1); + await rdbStore.executeSql(CREATE_TABLE_TEST); + ``` + +2. Insert data. + 1. Create a **ValuesBucket** to store the data you need to insert. + 2. Call the **insert()** method to insert data into the RDB store. + + The sample code is as follows: + + ``` + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} + let insertPromise = rdbStore.insert("test", valueBucket) + ``` + +3. Query data. + 1. Create an **RdbPredicates** object to specify query conditions. + 2. Call the **query()** method to query data. + 3. Call the **ResultSet()** method to obtain the query result. + + The sample code is as follows: + + ``` + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("name", "Tom") + let resultSet = await rdbStore.query(predicates) + + resultSet.goToFirstRow() + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + + resultSet.close() + ``` + +4. Set the distributed tables to be synchronized. + 1. Set the distributed tables. + 2. Check whether the setting is successful. + + The sample code is as follows: + + ``` + let promise = rdbStore.setDistributedTables(["test"]) + promise.then(() => { + console.info("setDistributedTables success.") + }).catch((err) => { + console.info("setDistributedTables failed."") + }) + ``` + + 5. Synchronize data across devices. + 1. Constructs an **RdbPredicates** object to specify remote devices within the network to be synchronized. + 2. Call the **sync()** method to synchronize data. + 3. Check whether the data synchronization is successful. The sample code is as follows: ``` - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} - let insertPromise = rdbStore.insert("test", valueBucket) + let predicate = new dataRdb.RdbPredicates('test') + predicate.inDevices(['12345678abcde']) + let promise = rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicate) + promise.then(result) { + console.log('sync done.') + for (let i = 0; i < result.length; i++) { + console.log('device=' + result[i][0] + ' status=' + result[i][1]) + } + }).catch((err) => { + console.log('sync failed') + }) ``` -3. Query data. - - 1. Create an **RdbPredicates** object to specify query conditions. - 2. Call the **query \(\)** method to query data in the RDB store. - 3. Call the **ResultSet\(\)** method to obtain the query result. +6. Subscribe to distributed data. + 1. Register an observer to listen for distributed data changes. + 2. When data in the RDB store changes, a callback will be invoked to return the data changes. The sample code is as follows: ``` - let predicates = new dataRdb.RdbPredicates("test"); - predicates.equalTo("name", "Tom") - let resultSet = await rdbStore.query(predicates) - - resultSet.goToFirstRow() - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - resultSet.close() + function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + device[i] + ' data changed') + } + } + try { + rdbStore.on('dataChange', rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + } catch (err) { + console.log('register observer failed') + } ``` +7. Query data across devices. + 1. Obtain the distributed table name for a remote device based on the local table name. + 2. Call the **ResultSet()** method to obtain the query result. + + The sample code is as follows: + ``` + let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); + let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) + ``` diff --git a/en/application-dev/quick-start/configuring-openharmony-app-signature.md b/en/application-dev/quick-start/configuring-openharmony-app-signature.md index 55ba99b6f63ac78b2c0722c40ae73074d2a68278..d2d7da5cb09c862978fac8648d46a62baf5e6953 100644 --- a/en/application-dev/quick-start/configuring-openharmony-app-signature.md +++ b/en/application-dev/quick-start/configuring-openharmony-app-signature.md @@ -124,7 +124,7 @@ Refer to the following descriptions about the parameters in the command: ## Generating the App Profile -The profile contains the following inforamtion about the OpenHarmony app: bundle name, digital certificate information, certificate permissions that can be applied for by the app, and devices where the app can be debugged \(the device list will be empty if the app type is Release\). Each app package must contain a profile file. +The profile contains the following information about the OpenHarmony app: bundle name, digital certificate information, certificate permissions that can be applied for by the app, and devices where the app can be debugged \(the device list will be empty if the app type is Release\). Each app package must contain a profile file. Go to the **Sdk\\toolchains\\lib** directory, open the command-line tool, and run the following command. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 0c9b2efa1db28346d5d2ce1b22aee2d5047b186d..4e072772748b27c506c29b5ecf6d6fc8c3c2f1b3 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -36,6 +36,7 @@ - [App Storage Statistics](js-apis-storage-statistics.md) - [Volume Management](js-apis-volumemanager.md) - Account Management + - [OS Account Management](js-apis-osAccount.md) - [Distributed Account Management](js-apis-distributed-account.md) - [App Account Management](js-apis-appAccount.md) - Telephony Service diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png b/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png new file mode 100644 index 0000000000000000000000000000000000000000..2128f0852380b2895198ab725a2f9d299c480d84 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png differ diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 8a747168fbe34c82c02c7233881a1461da2706c5..0d008c7f831661dcc9d49bb8a8cf3273ede1a361 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -9,15 +9,15 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl' ``` -## System Capabilities -SystemCapability.Security.AccessToken - ## abilityAccessCtrl.createAtManager createAtManager(): AtManager Creates an **AtManager** instance, which is used for ability access control. +**System capability**: SystemCapability.Security.AccessToken + + **Return value** | Type| Description| @@ -38,25 +38,27 @@ Implements ability access control. verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> -Checks whether an application has been granted the specified permission. This method uses a promise to return the result. +Checks whether an application has been granted the specified permission. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.AccessToken **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes| ID of the application.| -| permissionName | string | Yes| Name of the permission to verify.| +| tokenID | number | Yes | ID of the application. | +| permissionName | string | Yes | Name of the permission to verify.| **Return value** -| Type| Description| +| Type | Description | | :------------ | :---------------------------------- | | Promise<GrantStatus> | Promise instance used to return the result.| **Example** ``` -const AtManager = abilityAccessCtrl.createAtManager(); +var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; let promise = AtManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { @@ -68,28 +70,30 @@ promise.then(data => { grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> -Grants a user granted permission to an application. This method uses a promise to return the result. +Grants a user granted permission to an application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS -Required permission: ohos.permission.GRANT_SENSITIVE_PERMISSIONS +**System capability**: SystemCapability.Security.AccessToken **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes| ID of the application.| -| permissionName | string | Yes| Name of the permission to grant.| -| permissionFlag | number | Yes| Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed.| +| tokenID | number | Yes | ID of the application. | +| permissionName | string | Yes | Name of the permission to grant.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** -| Type| Description| +| Type | Description | | :------------ | :---------------------------------- | | Promise<number> | Promise instance used to return the result.| **Example** ``` -const AtManager = abilityAccessCtrl.createAtManager(); +var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; let promise = AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { @@ -103,23 +107,25 @@ promise.then(data => { grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void -Grants a user granted permission to an application. This method uses an asynchronous callback to return the result. +Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS -Required permission: ohos.permission.GRANT_SENSITIVE_PERMISSIONS +**System capability**: SystemCapability.Security.AccessToken **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes| ID of the application.| -| permissionName | string | Yes| Name of the permission to grant.| -| permissionFlag | number | Yes| Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed.| +| tokenID | number | Yes | ID of the application. | +| permissionName | string | Yes | Name of the permission to grant.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | | callback | AsyncCallback<number> | Yes| Callback used to return the result.| **Example** ``` -const AtManager = abilityAccessCtrl.createAtManager(); +var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; let permissionFlag = 1; AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS",permissionFlag, data => { @@ -131,28 +137,30 @@ AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_P revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> -Revokes a user granted permission given to an application. This method uses a promise to return the result. +Revokes a user granted permission given to an application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS -Required permission: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS +**System capability**: SystemCapability.Security.AccessToken **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes| ID of the application.| -| permissionName | string | Yes| Name of the permission to revoke.| -| permissionFlag | number | Yes| Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed.| +| tokenID | number | Yes | ID of the application. | +| permissionName | string | Yes | Name of the permission to revoke.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** -| Type| Description| +| Type | Description | | :------------ | :---------------------------------- | | Promise<number> | Promise instance used to return the result.| **Example** ``` -const AtManager = abilityAccessCtrl.createAtManager(); +var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; let permissionFlag = 1; let promise = AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag); @@ -165,23 +173,25 @@ promise.then(data => { revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void -Revokes a user granted permission given to an application. This method uses an asynchronous callback to return the result. +Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS -Required permission: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS +**System capability**: SystemCapability.Security.AccessToken **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes| ID of the application.| -| permissionName | string | Yes| Name of the permission to revoke.| -| permissionFlag | number | Yes| Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed.| +| tokenID | number | Yes | ID of the application. | +| permissionName | string | Yes | Name of the permission to revoke.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | | callback | AsyncCallback<number> | Yes| Callback used to return the result.| **Example** ``` -const AtManager = abilityAccessCtrl.createAtManager(); +var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS",permissionFlag, data => { console.log(`callback: data->${JSON.stringify(data)}`); @@ -192,25 +202,27 @@ AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_ getPermissionFlags(tokenID: number, permissionName: string): Promise<number> -Obtains the flags of the specified permission of a given application. This method uses a promise to return the result. +Obtains the flags of the specified permission of a given application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.AccessToken **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes| ID of the application.| -| permissionName | string | Yes| Name of the permission to query.| +| tokenID | number | Yes | ID of the application. | +| permissionName | string | Yes | Name of the permission to query.| **Return value** -| Type| Description| +| Type | Description | | :------------ | :---------------------------------- | | Promise<number> | Promise instance used to return the result.| **Example** ``` -const AtManager = abilityAccessCtrl.createAtManager(); +var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; let promise = AtManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { @@ -222,7 +234,9 @@ promise.then(data => { Enumerates the permission grant states. -| Name| Default Value| Description| +**System capability:** SystemCapability.Security.AccessToken + +| Name | Default Value | Description | | ----------------------------- | ---------------------- | ----------------------- | -| PERMISSION_DENIED | -1 | Permission denied.| -| PERMISSION_GRANTED | 0 | Permission granted.| +| PERMISSION_DENIED | -1 | Permission denied. | +| PERMISSION_GRANTED | 0 | Permission granted. | diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md index 9a3457468bf95e3ca81dda932a425999593ea855..e1bae182816c3b58d503b4f3e34ba36c30782d33 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md @@ -13,7 +13,7 @@ Provides extension running information. The extension running information is obtained through an **abilityManager** instance. - + ``` import abilitymanager from '@ohos.application.abilityManager'; abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { @@ -24,30 +24,34 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { ### Attributes +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extension | ElementName | Yes| No| Information that matches an extension.
System capability: SystemCapability.Ability.AbilityRuntime.Core| -| pid | number | Yes| No| Process ID.
System capability: SystemCapability.Ability.AbilityRuntime.Core| -| uid | number | Yes| No| User ID.
System capability: SystemCapability.Ability.AbilityRuntime.Core| -| processName | string | Yes| No| Process name.
System capability: SystemCapability.Ability.AbilityRuntime.Core| -| startTime | number | Yes| No| Extension start time.
System capability: SystemCapability.Ability.AbilityRuntime.Core| -| clientPackage | Array<String> | Yes| No| Names of all packages in the process.
System capability: SystemCapability.Ability.AbilityRuntime.Core| -| type | [bundle.ExtensionAbilityType](#bundle-extensionabilitytype) | Yes| No| Extension type.
System capability: SystemCapability.Ability.AbilityRuntime.Core| +| extension | ElementName | Yes| No| Information that matches an extension.| +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| startTime | number | Yes| No| Extension start time.| +| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| +| type | [bundle.ExtensionAbilityType](#bundle-extensionabilitytype) | Yes| No| Extension type.| ## bundle.ExtensionAbilityType -Enumerates the extension types. +Enumerates extension types. + +**System capability**: SystemCapability.BundleManager.BundleFramework | Name| Value| Description| | -------- | -------- | -------- | -| FORM | 0 | Extension information of the form type.
System capability: SystemCapability.BundleManager.BundleFramework| -| WORK_SCHEDULER | 1 | Extension information of the work scheduler type.
System capability: SystemCapability.BundleManager.BundleFramework| -| INPUT_METHOD | 2 | Extension information of the input method type.
System capability: SystemCapability.BundleManager.BundleFramework| -| SERVICE | 3 | Extension information of the service type.
System capability: SystemCapability.BundleManager.BundleFramework| -| ACCESSIBILITY | 4 | Extension information of the accessibility type.
System capability: SystemCapability.BundleManager.BundleFramework| -| DATA_SHARE | 5 | Extension information of the data share type.
System capability: SystemCapability.BundleManager.BundleFramework| -| FILE_SHARE | 6 | Extension information of the file share type.
System capability: SystemCapability.BundleManager.BundleFramework| -| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type.
System capability: SystemCapability.BundleManager.BundleFramework| -| WALLPAPER | 8 | Extension information of the wallpaper type.
System capability: SystemCapability.BundleManager.BundleFramework| -| UNSPECIFIED | 9 | Extension information of the unspecified type.
System capability: SystemCapability.BundleManager.BundleFramework| +| FORM | 0 | Extension information of the form type. | +| WORK_SCHEDULER | 1 | Extension information of the work scheduler type. | +| INPUT_METHOD | 2 | Extension information of the input method type. | +| SERVICE | 3 | Extension information of the service type. | +| ACCESSIBILITY | 4 | Extension information of the accessibility type. | +| DATA_SHARE | 5 | Extension information of the data share type. | +| FILE_SHARE | 6 | Extension information of the file share type. | +| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type. | +| WALLPAPER | 8 | Extension information of the wallpaper type. | +| UNSPECIFIED | 9 | Extension information of the unspecified type. | diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index 10ac56bb7e13b598ae6d30cae770b5dcefcaee82..1233939892fc155a982ad48fe236eabbdfe3b822 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -1,5 +1,5 @@ # Fault Logger -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -8,14 +8,13 @@ import faultLogger from '@ohos.faultLogger' ``` -## System Capabilities - -SystemCapability.HiviewDFX.Hiview.FaultLogger ## FaultType Enumerates the fault types. +**System capability**: SystemCapability.HiviewDFX.Hiview.FaultLogger + | Name| Default Value| Description| | -------- | -------- | -------- | | NO_SPECIFIC | 0 | No specific fault type.| @@ -27,6 +26,8 @@ Enumerates the fault types. Defines the data structure of the fault log information. +**System capability**: SystemCapability.HiviewDFX.Hiview.FaultLogger + | Name| Type| Description| | -------- | -------- | -------- | | pid | number | Process ID of the faulty process.| @@ -42,14 +43,16 @@ Defines the data structure of the fault log information. querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void -Obtains the fault information about the current process. This method uses a callback to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. +Obtains the fault information about the current process. This API uses a callback to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. + +**System capability**: SystemCapability.HiviewDFX.Hiview.FaultLogger **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | faultType | [FaultType](#faulttype) | Yes| Fault type.| -| callback | AsyncCallbackArray<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. +| callback | AsyncCallbackArray<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. **Example** @@ -73,14 +76,16 @@ function queryFaultLogCallback(error, value) { } } } -faultLogger.querySelfFaultLog(faultlogger.FaultType.JS_CRASH, queryFaultLogCallback); +faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); ``` ## faultLogger.querySelfFaultLog -querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>>; +querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> + +Obtains the fault information about the current process. This API uses a promise to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. -Obtains the fault information about the current process. This method uses a promise to return the fault information array obtained, which contains a maximum of 10 pieces of fault information. +**System capability**: SystemCapability.HiviewDFX.Hiview.FaultLogger **Parameters** @@ -92,25 +97,27 @@ Obtains the fault information about the current process. This method uses a prom | Type| Description| | -------- | -------- | -| Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise used to return the fault information array. You can obtain the fault information instance in its **then()** method or use **await**.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval.| +| Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise used to return the fault information array. You can obtain the fault information instance in its **then()** method or use **await**.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval.| **Example** ``` -let value = await faultLogger.querySelfFaultLog(faultlogger.FaultType.JS_CRASH); -if (value) { - console.info("value length is " + value.length); - let len = value.length; - for (let i = 0; i < len; i++) { - console.info("log: " + i); - console.info("Log pid: " + value[i].pid); - console.info("Log uid: " + value[i].uid); - console.info("Log type: " + value[i].type); - console.info("Log ts: " + value[i].ts); - console.info("Log reason: " + value[i].reason); - console.info("Log module: " + value[i].module); - console.info("Log summary: " + value[i].summary); - console.info("Log text: " + value[i].fullLog); +async function getLog() { + let value = await faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH); + if (value) { + console.info("value length is " + value.length); + let len = value.length; + for (let i = 0; i < len; i++) { + console.info("log: " + i); + console.info("Log pid: " + value[i].pid); + console.info("Log uid: " + value[i].uid); + console.info("Log type: " + value[i].type); + console.info("Log ts: " + value[i].ts); + console.info("Log reason: " + value[i].reason); + console.info("Log module: " + value[i].module); + console.info("Log summary: " + value[i].summary); + console.info("Log text: " + value[i].fullLog); + } } } ``` diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md new file mode 100644 index 0000000000000000000000000000000000000000..3956505f311775d34c41c3e98b41b8d7ab882243 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -0,0 +1,448 @@ +# Data Request + +>![](public_sys-resources/icon-note.gif) **NOTE:** +> +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> + +## Modules to Import + +``` +import http from '@ohos.net.http'; +``` + +## Complete Example + +``` +import http from '@ohos.net.http'; + +// Each httpRequest corresponds to an HttpRequestTask object and cannot be reused. +let httpRequest = http.createHttp(); +// This API is used to subscribe to the HTTP response header, which is returned earlier than httpRequest. It is up to you whether to listen for HTTP Response Header events. +// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+ +httpRequest.on('headersReceive', (data) => { + console.info('header: ' + data.header); +}); +httpRequest.request( + // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL. You can set the parameters of the GET request in extraData. + "EXAMPLE_URL", + { + method: 'POST', // Optional. The default value is GET. + // Add the header field based on your service requirements. + header: { + 'Content-Type': 'application/json' + }, + // This field is used to transfer content when the POST request is used. You can set request parameters in extraData as needed. + + extraData: { + "data": "data to send", + }, + connectTimeout: 60000, // Optional. The default value is **60000**, in ms. + readTimeout: 60000, // Optional. The default value is **60000**, in ms. + },(err, data) => { + if (!err) { + // data.result contains the HTTP response. It is up to you whether to parse the content. + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + // data.header contains the HTTP response header. It is up to you whether to parse the content. + console.info('header:' + data.header); + console.info('cookies:' + data.cookies); // 8+ + } else { + console.info('error:' + err); + // Call the destroy function to destroy the request after use. + httpRequest.destroy(); + } + } +); +``` + +## http.createHttp + +createHttp\(\): HttpRequest + +Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An HttpRequest object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an HttpRequest object for each HTTP request. + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :---------- | :----------------------------------------------------------- | +| HttpRequest | An **HttpRequest **object, which contains the **request**, **destroy**, **on**, or **off** method.| + +**Example** + +``` +import http from '@ohos.net.http'; +let httpRequest = http.createHttp(); +``` + + +## HttpRequest + +Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. + +### request + +request\(url: string, callback: AsyncCallback\\):void + +Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ----------------------- | +| url | string | Yes | URL for initiating an HTTP request.| +| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | + +**Example** + +``` +httpRequest.request("EXAMPLE_URL", (err, data) => { + if (!err) { + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + console.info('header:' + data.header); + console.info('cookies:' + data.cookies); // 8+ + } else { + console.info('error:' + err.data); + } +}); +``` + +### request + +request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\):void + +Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| +| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | + +**Example** + +``` +httpRequest.request("EXAMPLE_URL", +{ + method: 'GET', + header: { + 'Content-Type': 'application/json' + }, + readTimeout: 60000, + connectTimeout: 60000 +},(err, data) => { + if (!err) { + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + console.info('header:' + data.header); + console.info('cookies:' + data.cookies); // 8+ + console.info('header['Content-Type']:' + data.header['Content-Type']); + console.info('header['Status-Line']:' + data.header['Status-Line']); + console.info('header.Date:' + data.header.Date); + console.info('header.Server:' + data.header.Server); + } else { + console.info('error:' + err.data); + } +}); +``` + + +### request + +request\(url: string, options? : HttpRequestOptions\): Promise + +Initiates an HTTP request to a given URL. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------ | ---- | -------------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| + +**Return Value** + +| Type | Description | +| :-------------------- | :-------------------------------- | +| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| + + +**Example** + +``` +let promise = httpRequest.request("EXAMPLE_URL", { + method: "GET", + connectTimeout: 60000, + readTimeout: 60000, + header: { + 'Content-Type': 'application/json' + } +}); +promise.then((value) => { + console.info('Result:' + value.result); + console.info('code:' + value.responseCode); + console.info('header:' + value.header); + console.info('cookies:' + value.cookies); // 8+ + console.info('header['Content-Type']:' + value.header['Content-Type']); + console.info('header['Status-Line']:' + value.header['Status-Line']); + console.info('header.Date:' + value.header.Date); + console.info('header.Server:' + value.header.Server); +}).catch((err) => { + console.error(`errCode:${err.code}, errMessage:${err.data}`); +}); +``` + +### destroy + +destroy\(\): void + +Destroys an HTTP request. + +**System capability**: SystemCapability.Communication.NetStack + +**Example** + +``` +httpRequest.destroy(); +``` + +### on\('headerReceive'\) + +on\(type: 'headerReceive', callback: AsyncCallback\): void + +Registers an observer for HTTP Response Header events. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +> This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value is **headerReceive**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +httpRequest.on('headerReceive', (err, data) => { + if (!err) { + console.info('header: ' + data.header); + } else { + console.info('error:' + err.data); + } +}); +``` + + +### off\('headerReceive'\) + +off\(type: 'headerReceive', callback?: AsyncCallback\): void + +Unregisters the observer for HTTP Response Header events. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +> +>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)8+](#offheadersreceive8) instead. +> +>2. You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------- | +| type | string | Yes | Event type. The value is **headerReceive**.| +| callback | AsyncCallback\ | No | Callback used to return the result. | + +**Example** + +``` +httpRequest.on('headerReceive', (err, data) => { + if (!err) { + console.info('header: ' + data.header); + } else { + console.info('error:' + err.data); + } +}); +httpRequest.off('headerReceive'); +``` + +### on\('headersReceive'\)8+ + +on\(type: 'headersReceive', callback: Callback\): void + +Registers an observer for HTTP Response Header events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | ---------------------------------- | +| type | string | Yes | Event type. The value is **headersReceive**.| +| callback | Callback\ | Yes | Callback used to return the result. | + +**Example** + +``` +httpRequest.on('headersReceive', (data) => { + console.info('header: ' + data.header); +}); +``` + + +### off\('headersReceive'\)8+ + +off\(type: 'headersReceive', callback?: Callback\): void + +Unregisters the observer for HTTP Response Header events. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **headersReceive**.| +| callback | Callback\ | No | Callback used to return the result. | + +**Example** + +``` +httpRequest.off('headersReceive'); +``` + +### once\('headersReceive'\)8+ + +once\(type: 'headersReceive', callback: Callback\): void + +Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | ---------------------------------- | +| type | string | Yes | Event type. The value is **headersReceive**.| +| callback | Callback\ | Yes | Callback used to return the result. | + +**Example** + +``` +httpRequest.once('headersReceive', (data) => { + console.info('header: ' + data.header); +}); +``` + +## HttpRequestOptions + +Specifies the type and value range of the optional parameters in the HTTP request. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- | +| method | [RequestMethod](#requestmethod) | No | Request method. | +| extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.8+
- To pass in a string object, you first need to encode the object on your own.8+ | +| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.| +| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | +| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | + +## RequestMethod + +Defines an HTTP request method. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Value | Description | +| :------ | ------- | :------------------ | +| OPTIONS | OPTIONS | OPTIONS method.| +| GET | GET | GET method. | +| HEAD | HEAD | HEAD method. | +| POST | POST | POST method. | +| PUT | PUT | PUT method. | +| DELETE | DELETE | DELETE method. | +| TRACE | TRACE | TRACE method. | +| CONNECT | CONNECT | CONNECT method.| + +## ResponseCode + +Enumerates the response codes for an HTTP request. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Value | Description | +| ----------------- | ---- | ------------------------------------------------------------ | +| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | +| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | +| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | +| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | +| NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. | +| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | +| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | +| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | +| MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.| +| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | +| SEE_OTHER | 303 | "See Other." The response to the request can be found under a different URI. | +| NOT_MODIFIED | 304 | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified. | +| USE_PROXY | 305 | "Use Proxy." The requested resource can only be accessed through the proxy. | +| BAD_REQUEST | 400 | "Bad Request." The request could not be understood by the server due to incorrect syntax. | +| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication. | +| PAYMENT_REQUIRED | 402 | "Payment Required." This code is reserved for future use. | +| FORBIDDEN | 403 | "Forbidden." The server understands the request but refuses to process it. | +| NOT_FOUND | 404 | "Not Found." The server does not find anything matching the Request-URI. | +| BAD_METHOD | 405 | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI. | +| NOT_ACCEPTABLE | 406 | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request. | +| PROXY_AUTH | 407 | "Proxy Authentication Required." The request requires user authentication with the proxy. | +| CLIENT_TIMEOUT | 408 | "Request Timeout." The client fails to generate a request within the timeout period. | +| CONFLICT | 409 | "Conflict." The request cannot be fulfilled due to a conflict with the current state of the resource. Conflicts are most likely to occur in response to a PUT request. | +| GONE | 410 | "Gone." The requested resource has been deleted permanently and is no longer available. | +| LENGTH_REQUIRED | 411 | "Length Required." The server refuses to process the request without a defined Content-Length. | +| PRECON_FAILED | 412 | "Precondition Failed." The precondition in the request is incorrect. | +| ENTITY_TOO_LARGE | 413 | "Request Entity Too Large." The server refuses to process a request because the request entity is larger than the server is able to process. | +| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | +| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | +| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | +| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | +| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| +| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | +| GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. | +| VERSION | 505 | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request. | + +## HttpResponse + +Defines the response to an HTTP request. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| +| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. The error code can be one of the following:
- 200: common error
- 202: parameter error
- 300: I/O error| +| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| +| cookies8+ | Array\ | Yes | Cookies returned by the server. | diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index f913c7697501e15ee06c505fe9e5e7ed8d471973..35a68b7ef9f6ce411aa9c75a13b4df65a5de4ddd 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -10,7 +10,7 @@ import LinkedList from '@ohos.util.LinkedList' ``` -## System Capabilities +## System Capability SystemCapability.Utils.Lang @@ -452,7 +452,7 @@ callbackfn | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the entry that is currently traversed.| | index | number | No| Position index of the entry that is currently traversed.| -| LinkedList | LinkedList<T> | No| Instance that invokes the **forEach** method.| +| LinkedList | LinkedList<T> | No| Instance that invokes the **forEach** API.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md new file mode 100644 index 0000000000000000000000000000000000000000..9d04af32345f913b519ce9645d66a80ff4d92191 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -0,0 +1,974 @@ +# Network Connection Management + + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```javascript +import connection from '@ohos.net.connection' +``` + +## connection.getDefaultNet + +getDefaultNet(callback: AsyncCallback\): void + +Obtains the default active data network. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result.| + +**Example** + +```javascript +connection.getDefaultNet(function (error, netHandle) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(netHandle)) +}) +``` + +## connection.getDefaultNet + +getDefaultNet(): Promise\ + +Obtains the default active data network. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return Value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.| + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + console.log(JSON.stringify(netHandle)) +}) +``` + +## connection.hasDefaultNet + +hasDefaultNet(callback: AsyncCallback\): void + +Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated.| + +**Example** + +```javascript +connection.hasDefaultNet(function (error, has) { + console.log(JSON.stringify(error)) + console.log(has) +}) +``` + +## connection.hasDefaultNet + +hasDefaultNet(): Promise\ + +Checks whether the default data network is activated. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return Value** + +| Type | Description | +| ----------------- | ----------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** indicates that the default data network is activated.| + +**Example** + +```javascript +connection.hasDefaultNet().then(function (has) { + console.log(has) +}) +``` + +## connection.getAllNets + +getAllNets(callback: AsyncCallback<Array<NetHandle>>): void + +Obtains the list of all active data networks. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result.| + +**Example** + +``` +connection.getAllNets(function (error, nets) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(nets)) +}); +``` + + +## connection.getAllNets + +getAllNets(): Promise<Array<NetHandle>> + +Obtains the list of all active data networks. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return Value** +| Type| Description| +| -------- | -------- | +| Promise<Array<[NetHandle](#nethandle)>> | Promise used to return the result.| + +**Example** + +``` +connection.getAllNets().then(function (nets) { + console.log(JSON.stringify(nets)) +}); +``` + +## connection.getConnectionProperties + +getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void + +Obtains connection properties of the network corresponding to given network handle. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| +| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. | + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + connection.getConnectionProperties(netHandle, function (error, info) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(info)) + }) +}) +``` + +## connection.getConnectionProperties + +getConnectionProperties(netHandle: NetHandle): Promise\ + +Obtains connection properties of the network corresponding to **netHandle**. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| + +**Return Value** + +| Type | Description | +| ------------------------------------------------------- | --------------------------------- | +| Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.| + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + connection.getConnectionProperties(netHandle).then(function (info) { + console.log(JSON.stringify(info)) + }) +}) +``` + +## connection.getNetCapabilities + +getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): void + +Obtains capability information of the network corresponding to **netHandle**. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------------- | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| +| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. | + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + connection.getNetCapabilities(netHandle, function (error, info) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(info)) + }) +}) +``` + +## connection.getNetCapabilities + +getNetCapabilities(netHandle: NetHandle): Promise\ + +Obtains capability information of the network corresponding to **netHandle**. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| + +**Return Value** + +| Type | Description | +| --------------------------------------------- | --------------------------------- | +| Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.| + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + connection.getNetCapabilities(netHandle).then(function (info) { + console.log(JSON.stringify(info)) + }) +}) +``` + +## connection.reportNetConnected + +reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void + +Reports connection of the data network. This API uses an asynchronous callback to return the result. + +** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +``` +connection.getDefaultNet().then(function (netHandle) { + connection.reportNetConnected(netHandle, function (error) { + console.log(JSON.stringify(error)) + }); +}); +``` + + +## connection.reportNetConnected + +reportNetConnected(netHandle: NetHandle): Promise<void> + +Reports connection of the data network. This API uses a promise to return the result. + +** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| + +**Return Value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +``` +connection.getDefaultNet().then(function (netHandle) { + connection.reportNetConnected(netHandle).then(function () { + console.log(`report success`) + }); +}); +``` + + +## connection.reportNetDisconnected + +reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void + +Reports disconnection of the data network. This API uses an asynchronous callback to return the result. + +** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +``` +connection.getDefaultNet().then(function (netHandle) { + connection.reportNetDisconnected(netHandle, function (error) { + console.log(JSON.stringify(error)) + }); +}); +``` + + +## connection.reportNetDisconnected + +reportNetDisconnected(netHandle: NetHandle): Promise<void> + +Reports disconnection of the data network. This API uses a promise to return the result. + +** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| + +**Return Value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +``` +connection.getDefaultNet().then(function (netHandle) { + connection.reportNetDisconnected(netHandle).then(function () { + console.log(`report success`) + }); +}); +``` + +## connection.getAddressesByName + +getAddressesByName(host: string, callback: AsyncCallback\>): void + +Resolves the host name by using the default network to obtain all IP addresses. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| host | string | Yes | Host name to be resolved.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +``` +let host = "xxxx"; +connection.getAddressesByName(host, function (error, addresses) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(addresses)) +}) +``` + +## connection.getAddressesByName + +getAddressesByName(host: string): Promise\> + +Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| host | string | Yes | Host name to be resolved.| + +**Return Value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +``` +let host = "xxxx"; +connection.getAddressesByName(host).then(function (addresses) { + console.log(JSON.stringify(addresses)) +}) +``` + +## connection.createNetConnection + +createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection + +Obtains the handle of the network specified by **netSpecifier**. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. | +| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.| + +**Return Value** + +| Type | Description | +| ------------------------------- | -------------------- | +| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.| + +**Example** + +```javascript +// Default network +let netConnection = connection.createNetConnection() + +// Cellular network +let netConnectionCellular = connection.createNetConnection({ + netCapabilities: { + bearerTypes: [NetBearType.BEARER_CELLULAR] + } +}) +``` + +## NetConnection + +Represents the network connection handle. + +### on('netAvailable') + +on(type: 'netAvailable', callback: Callback\): void + +Registers a listener for **netAvailable** events. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed to **netAvailable**.
**netAvailable**: event indicating that the data network is available.| +| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | + +**Example** + +```javascript +netConnection.on('netAvailable', function (data) { + console.log(JSON.stringify(data)) +}) +``` + +### on('netCapabilitiesChange') + +on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void + +Registers a listener for **netCapabilitiesChange** events. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.
**netCapabilitiesChange**: event indicating that he network capabilities have changed.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. | + +**Example** + +```javascript +netConnection.on('netCapabilitiesChange', function (data) { + console.log(JSON.stringify(data)) +}) +``` + +### on('netConnectionPropertiesChange') + +on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void + +Registers a listener for **netConnectionPropertiesChange** events. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. | + +**Example** + +```javascript +netConnection.on('netConnectionPropertiesChange', function (data) { + console.log(JSON.stringify(data)) +}) +``` + +### on('netBlockStatusChange') + +on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void + +Registers a listener for **netBlockStatusChange** events. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.
**netBlockStatusChange**: event indicating a change in the network blocking status.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the result. | + +**Example** + +```javascript +netConnection.on('netBlockStatusChange', function (data) { + console.log(JSON.stringify(data)) +}) +``` + +### on('netLost') + +on(type: 'netLost', callback: Callback\): void + +Registers a listener for **netLost** events. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed to **netLost**.
netLost: event indicating that the network is interrupted or normally disconnected.| +| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | + +**Example** + +```javascript +let netConnection1 = connection.createNetConnection() +netConnection1.on('netLost', function (data) { + console.log(JSON.stringify(data)) +}) +``` + +### on('netUnavailable') + +on(type: 'netUnavailable', callback: Callback\): void + +Registers a listener for **netUnavailable** events. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed to **netUnavailable**.
**netUnavailable**: event indicating that the network is unavailable.| +| callback | Callback\ | Yes | Callback used to return the result. | + +**Example** + +```javascript +netConnection.on('netUnavailable', function (data) { + console.log(JSON.stringify(data)) +}) +``` + +### register + +register(callback: AsyncCallback\): void + +Registers a listener for network status changes. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```javascript +netConnection.register(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +### unregister + +unregister(callback: AsyncCallback\): void + +Unregisters the listener for network status changes. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```javascript +netConnection.unregister(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## NetHandle + +Defines the handle of the data network. + +Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** object. + +**System capability**: SystemCapability.Communication.NetManager.Core + +### Parameters + +| Name| Type | Description | +| ------ | ------ | ------------------------- | +| netId | number | Network ID. The value must be greater than or equal to 100.| + +### bindSocket + +bindSocket(socketParam: TCPSocket | UDPSocket, callback: AsyncCallback<void>): void + +Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | ---------------- | +| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +``` +// Bind the TCPSocket object. +connection.getDefaultNet().then(function (netHandle) { + let tcpSocket = socket.constructTCPSocketInstance() + netHandle.bindSocket(tcpSocket, (function (error) { + console.log(JSON.stringify(error)) + })) +}) +// Bind the UDPSocket object. +connection.getDefaultNet().then(function (netHandle) { + let udpSocket = socket.constructUDPSocketInstance() + netHandle.bindSocket(udpSocket, (function (error) { + console.log(JSON.stringify(error)) + })) +}) +``` + + +### bindSocket + +bindSocket(socketParam: TCPSocket | UDPSocket): Promise<void> + +Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.| + +**Return Value** +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +``` +// Bind the TCPSocket object. +connection.getDefaultNet().then(function (netHandle) { + let tcpSocket = socket.constructTCPSocketInstance() + netHandle.bindSocket(tcpSocket).then(function () { + console.log("bind socket success") + }) +}) +// Bind the UDPSocket object. +connection.getDefaultNet().then(function (netHandle) { + let udpSocket = socket.constructUDPSocketInstance() + netHandle.bindSocket(udpSocket).then(function () { + console.log("bind socket success") + }) +}) +``` + +### getAddressesByName + +getAddressesByName(host: string, callback: AsyncCallback\>): void + +Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| host | string | Yes | Host name to be resolved.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + let host = "xxxx"; + netHandle.getAddressesByName(host, function (error, addresses) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(addresses)) + }) +}) +``` + +### getAddressesByName + +getAddressesByName(host: string): Promise\> + +Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| host | string | Yes | Host name to be resolved.| + +**Return Value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + let host = "xxxx"; + netHandle.getAddressesByName(host).then(function (addresses) { + console.log(JSON.stringify(addresses)) + }) +}) +``` + +### getAddressByName + +getAddressByName(host: string, callback: AsyncCallback\): void + +Resolves the host name by using the corresponding network to obtain the first IP address. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------ | +| host | string | Yes | Host name to be resolved.| +| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. | + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + let host = "xxxx"; + netHandle.getAddressByName(host, function (error, address) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(address)) + }) +}) +``` + +### getAddressByName + +getAddressByName(host: string): Promise\ + +Resolves the host name by using the corresponding network to obtain the first IP address. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| host | string | Yes | Host name to be resolved.| + +**Return Value** + +| Type | Description | +| ----------------------------------- | ------------------------------- | +| Promise\<[NetAddress](#netaddress)> | Promise used to return the result.| + +**Example** + +```javascript +connection.getDefaultNet().then(function (netHandle) { + let host = "xxxx"; + netHandle.getAddressByName(host).then(function (address) { + console.log(JSON.stringify(address)) + }) +}) +``` + +## NetSpecifier + +Provides an instance that bears data network capabilities. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| netCapabilities | [NetCapabilities](#netcapabilities) | Network transmission capabilities and bearer types of the data network. | +| bearerPrivateIdentifier | string | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| + +## NetCapabilities + +Defines the network capability set. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| --------------------- | ---------------------------------- | ------------------------ | +| linkUpBandwidthKbps | number | Uplink (from the device to the network) bandwidth.| +| linkDownBandwidthKbps | number | Downlink (from the network to the device) bandwidth.| +| networkCap | Array<[NetCap](#netcap)> | Network capability. | +| bearerTypes | Array<[NetBearType](#netbearType)> | Network type. | + +## NetCap + +Defines the network capability. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| +| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| +| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| +| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).| +| NET_CAPABILITY_VALIDATED | 16 | The network is available. | + +## NetBearType + +Defines the network type. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| --------------- | ---- | ----------- | +| BEARER_CELLULAR | 0 | Cellular network | +| BEARER_WIFI | 1 | Wi-Fi network| +| BEARER_ETHERNET | 3 | Ethernet network| + +## ConnectionProperties + +Defines the network connection properties. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ------------- | ---------------------------------- | ---------------- | +| interfaceName | string | NIC card name. | +| domains | string | Domain. The default value is **""**.| +| linkAddresses | Array<[LinkAddress](#linkaddress)> | Link information. | +| routes | Array<[RouteInfo](#routeinfo)> | Route information. | +| dnses | Array<[NetAddress](#netaddress)> | Network address. For details, see [NetAddress](#netaddress).| +| mtu | number | Maximum transmission unit (MTU). | + +## LinkAddress + +Network link information. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ------------ | ------------------------- | -------------------- | +| address | [NetAddress](#netaddress) | Link address. | +| prefixLength | number | Length of the link address prefix.| + +## RouteInfo + +Network route information. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| -------------- | --------------------------- | ---------------- | +| interface | string | NIC card name. | +| destination | [LinkAddress](#linkaddress) | Destination IP address. | +| gateway | [NetAddress](#netaddress) | Gateway address. | +| hasGateway | boolean | Whether a gateway is present. | +| isDefaultRoute | boolean | Whether the route is the default route.| + +## NetAddress + +Defines the network address. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ------- | ------ | ------------------------------ | +| address | string | Network address. | +| family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| +| port | number | Port number. The value ranges from **0** to **65535**. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md new file mode 100644 index 0000000000000000000000000000000000000000..c85c006e1149df12f4c965243b5ad91fce573480 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -0,0 +1,1647 @@ +# OS Account Management + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import account_osAccount from '@ohos.account.osAccount'; +``` + +## System Capabilities + +SystemCapability.Account.OsAccount + +## account_osAccount.getAccountManager + +getAccountManager(): AccountManager + +Obtains an **AccountManager** instance. + +- Return value + | Type| Description| + | -------- | -------- | + | [AccountManager](#accountmanager) | **AccountManager** instance obtained.| + +- Example + ``` + const accountManager = account_osAccount.getAccountManager(); + ``` + +## OsAccountType +Enumerates OS account types. + | Name| Default Value| Description| + | -------- | -------- | -------- | + | ADMIN | 0 | Administrator account| + | NORMAL | 1 | Normal account| + | GUEST | 2 | Guest account| + +## AccountManager + +Provides methods to manage OS accounts. + +### activateOsAccount + +activateOsAccount(localId: number, callback: AsyncCallback<void>): void + +Activates an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------- | ---- | -------------------- | + | localId | number | Yes | ID of the OS account to activate.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +- Example + + Activate OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.activateOsAccount(localId, (err)=>{ + console.log("activateOsAccount err:" + JSON.stringify(err)); + }); + ``` + +### activateOsAccount + +activateOsAccount(localId: number): Promise<void> + +Activates an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | Yes | ID of the OS account to activate.| + +- Return value + + | Type | Description | + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + Activate OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.activateOsAccount(localId).then(() => { + console.log("activateOsAccount success"); + }).catch((err) => { + console.log("activateOsAccount err:" + JSON.stringify(err)); + }); + ``` + +### isMultiOsAccountEnable + +isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void + +Checks whether multiple OS accounts are supported. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------- | ---- | ------------------------------ | + | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If multiple OS accounts are supported, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.isMultiOsAccountEnable((err, isEnabled) => { + console.log("isMultiOsAccountEnable err: " + JSON.stringify(err)); + console.log('isMultiOsAccountEnable isEnabled: ' + isEnabled); + }); + ``` + +### isMultiOsAccountEnable + +isMultiOsAccountEnable(): Promise<boolean> + +Checks whether multiple OS accounts are supported. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :--------------- | :---------------------------------- | + | Promise<boolean> | Promise used to return the result. If multiple OS accounts are supported, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.isMultiOsAccountEnable().then((isEnabled) => { + console.log('isMultiOsAccountEnable, isEnabled: ' + isEnabled); + }).catch((err) => { + console.log("isMultiOsAccountEnable err: " + JSON.stringify(err)); + }); + ``` + +### isOsAccountActived + +isOsAccountActived(localId: number, callback: AsyncCallback<boolean>): void + +Checks whether an OS account is activated. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------- | ---- | ------------------------------ | + | localId | number | Yes | ID of the target OS account. | + | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the OS account is activated, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + Check whether OS account 100 is activated. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var osLocalId = 100; + accountManager.isOsAccountActived(osLocalId, (err, isActive)=>{ + console.log("isOsAccountActived err:" + JSON.stringify(err)); + console.log("isOsAccountActived isActive:" + isActive); + }); + ``` + +### isOsAccountActived + +isOsAccountActived(localId: number): Promise<boolean> + +Checks whether an OS account is activated. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | Yes | ID of the target OS account.| + +- Return value + + | Type | Description | + | :--------------- | :---------------------------------- | + | Promise<boolean> | Promise used to return the result. If the OS account is activated, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + Check whether OS account 100 is activated. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var osLocalId = 100; + accountManager.isOsAccountActived(osLocalId).then((isActive) => { + console.log('isOsAccountActived, isActive: ' + isActive); + }).catch((err) => { + console.log("isOsAccountActived err: " + JSON.stringify(err)); + }); + ``` + +### isOsAccountConstraintEnable + +isOsAccountConstraintEnable(localId: number, constraint: string, callback: AsyncCallback<boolean>): void + +Checks whether the specified constraint is enabled for an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ---------- | ---------------------- | ---- | ------------------------------ | + | localId | number | Yes | ID of the target OS account.| + | [constraint](#constraints) | string | Yes | Constraint specified.| + | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the constraint is enabled for the OS account, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + Check whether OS account 100 is forbidden to use Wi-Fi. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.isOsAccountConstraintEnable(localId, "constraint.wifi", (err, isConstraintEnabled)=>{ + console.log("isOsAccountConstraintEnable err:" + JSON.stringify(err)); + console.log("isOsAccountConstraintEnable isConstraintEnabled:" + isConstraintEnabled); + }); + ``` + +### isOsAccountConstraintEnable + +isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boolean> + +Checks whether the specified constraint is enabled for an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | ---------------- | + | localId | number | Yes | ID of the target OS account.| + | [constraint](#constraints)| string | Yes | Constraint specified.| + +- Return value + + | Type | Description | + | :--------------- | :---------------------------------- | + | Promise<boolean> | Promise used to return the result. If the constraint is enabled for the OS account, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + Check whether OS account 100 is forbidden to use Wi-Fi. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.isOsAccountConstraintEnable(localId, "constraint.wifi").then((isConstraintEnabled) => { + console.log('isOsAccountConstraintEnable, isConstraintEnabled: ' + isConstraintEnabled); + }).catch((err) => { + console.log("isOsAccountConstraintEnable err: " + JSON.stringify(err)); + }); + ``` + +### isTestOsAccount + +isTestOsAccount(callback: AsyncCallback<boolean>): void + +Checks whether this OS account is a test account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------- | ---- | ------------------------------------------ | + | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the account is a test account, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.isTestOsAccount((err, isTest) => { + console.log("isTestOsAccount err: " + JSON.stringify(err)); + console.log('isTestOsAccount isTest: ' + isTest); + }); + ``` + +### isTestOsAccount + +isTestOsAccount(): Promise<boolean> + +Checks whether this OS account is a test account. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :--------------- | :---------------------------------- | + | Promise<boolean> | Promise used to return the result. If the account is a test account, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.isTestOsAccount().then((isTest) => { + console.log('isTestOsAccount, isTest: ' + isTest); + }).catch((err) => { + console.log("isTestOsAccount err: " + JSON.stringify(err)); + }); + ``` + +### isOsAccountVerified + +isOsAccountVerified(callback: AsyncCallback<boolean>): void + +Checks whether this OS account has been verified. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------- | ---- | ---------------------------------- | + | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the OS account has been verified, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.isOsAccountVerified((err, isVerified) => { + console.log("isOsAccountVerified err: " + JSON.stringify(err)); + console.log('isOsAccountVerified isVerified: ' + isVerified); + }); + ``` + +### isOsAccountVerified + +isOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void + +Checks whether an OS account has been verified. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------- | ---- | ---------------------------------- | + | localId | number | No | ID of the target OS account. | + | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the OS account has been verified, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.isOsAccountVerified((err, isVerified) => { + console.log("isOsAccountVerified err: " + JSON.stringify(err)); + console.log('isOsAccountVerified isVerified: ' + isVerified); + }); + ``` + +### isOsAccountVerified + +isOsAccountVerified(localId: number?): Promise<boolean> + +Checks whether an OS account has been verified. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | No | ID of the target OS account.| + +- Return value + + | Type | Description | + | :--------------- | :---------------------------------- | + | Promise<boolean> | Promise used to return the result. If the OS account has been verified, **true** will be returned. Otherwise, **false** will be returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.isOsAccountVerified().then((isVerified) => { + console.log('isOsAccountVerified, isVerified: ' + isVerified); + }).catch((err) => { + console.log("isOsAccountVerified err: " + JSON.stringify(err)); + }); + ``` + +### removeOsAccount + +removeOsAccount(localId: number, callback: AsyncCallback<void>): void + +Removes an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------- | ---- | ------------------------ | + | localId | number | Yes | ID of the OS account to remove. | + | callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + var createIocalId; + osAccountManager.createOsAccount("testAccountName", osaccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + createIocalId = osAccountInfo.localId; + )}; + accountManager.removeOsAccount(createIocalId, (err)=>{ + console.log("removeOsAccount err:" + JSON.stringify(err)); + }); + ``` + +### removeOsAccount + +removeOsAccount(localId: number): Promise<void> + +Removes an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | Yes | ID of the OS account to remove.| + +- Return value + + | Type | Description | + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + var createIocalId; + osAccountManager.createOsAccount("testAccountName", osaccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + createIocalId = osAccountInfo.localId; + )}; + createIocalId = osAccount.localId; + accountManager.removeOsAccount(createIocalId).then(() => { + console.log('removeOsAccount Success'); + }).catch(() => { + console.log("removeOsAccount err: " + JSON.stringify(err)); + }); + ``` + +### setOsAccountConstraints + +setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean,callback: AsyncCallback<void>): void + +Sets or removes constraints for an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ----------- | ------------------- | ---- | ------------------------------- | + | localId | number | Yes | ID of the target OS account. | + | [constraints](constraints)| Array<string> | Yes | List of constraints to set or remove. | + | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | + | callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +- Example + + Disable Wi-Fi for OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.setOsAccountConstraints(localId, ["constraint.wifi"], true, (err)=>{ + console.log("setOsAccountConstraints err:" + JSON.stringify(err)); + }); + ``` + +### setOsAccountConstraints + +setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean): Promise<void> + +Sets or removes constraints for an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ----------- | ------------- | ---- | ----------------------- | + | localId | number | Yes | ID of the target OS account. | + | [constraints](constraints)| Array<string> | Yes | List of constraints to set or remove.| + | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints.| + +- Return value + + | Type | Description | + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + Remove the constraint on Wi-Fi for OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.setOsAccountConstraints(localId, ["constraint.location.set"], false).then(() => { + console.log('setOsAccountConstraints Success'); + }).catch((err) => { + console.log("setOsAccountConstraints err: " + JSON.stringify(err)); + }); + ``` + +### setOsAccountName + +setOsAccountName(localId: number, localName: string, callback: AsyncCallback<void>): void + +Sets a name for an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | :-------- | ------------------- | ---- | ------------------------ | + | localId | number | Yes | ID of the target OS account. | + | localName | string | Yes | Account name to set. | + | callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +- Example + + Set the name of OS account 100 to **demoName**. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + var newName = "demoName"; + accountManager.setOsAccountName(localId, newName, (err)=>{ + console.debug("setOsAccountName err:" + JSON.stringify(err)); + }); + ``` + +### setOsAccountName + +setOsAccountName(localId: number, localName: string): Promise<void> + +Sets a name for an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | ----------------------- | + | localId | number | Yes | ID of the target OS account. | + | localName | string | Yes | Account name to set.| + +- Return value + + | Type | Description | + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + Set the name of OS account 100 to **demoName**. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + var nameLimit = "demoName"; + accountManager.setOsAccountName(localId, nameLimit).then(() => { + console.log('setOsAccountName Success'); + }).catch((err) => { + console.log("setOsAccountName err: " + JSON.stringify(err)); + }); + ``` + +### getCreatedOsAccountsCount + +getCreatedOsAccountsCount(callback: AsyncCallback<number>): void + +Obtains the number of OS accounts created. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ------------------------------ | + | callback | AsyncCallback<number> | Yes | Callback used to return the number of OS accounts created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getCreatedOsAccountsCount((err, accountCnt)=>{ + console.log("obtains the number of all os accounts created err:" + JSON.stringify(err)); + console.log("obtains the number of all os accounts created accountCnt:" + accountCnt); + }); + ``` + +### getCreatedOsAccountsCount + +getCreatedOsAccountsCount(): Promise<number> + +Obtains the number of OS accounts created. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<number> | Promise used to return the number of OS accounts created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getCreatedOsAccountsCount().then((accountCnt) => { + console.log('getCreatedOsAccountsCount, accountCnt: ' + accountCnt); + }).catch((err) => { + console.log("getCreatedOsAccountsCount err: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountLocalIdFromProcess + +getOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void + +Obtains the ID of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ----------------------------------------- | + | callback | AsyncCallback<number> | Yes | Callback used to return the account ID obtained.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountLocalIdFromProcess((err, accountID) => { + console.log("getOsAccountLocalIdFromProcess err: " + JSON.stringify(err)); + console.log('getOsAccountLocalIdFromProcess accountID: ' + accountID); + }); + ``` + +### getOsAccountLocalIdFromProcess + +getOsAccountLocalIdFromProcess(): Promise<number> + +Obtains the ID of the OS account to which the current process belongs. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<number> | Promise used to return the account ID obtained.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountLocalIdFromProcess().then((accountID) => { + console.log('getOsAccountLocalIdFromProcess, accountID: ' + accountID); + }).catch((err) => { + console.log("getOsAccountLocalIdFromProcess err: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountLocalIdFromUid + +getOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void + +Obtains the OS account ID based on the process UID. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | --------------------------------------- | + | uid | number | Yes | Process UID.| + | callback | AsyncCallback<number> | Yes | Callback used to return the OS account ID obtained.| + +- Example + + Obtain the ID of the OS account whose process UID is **12345678**. + + ``` + const accountManager = account_osAccount.getAccountManager(); + let uid = 12345678; + accountManager.getOsAccountLocalIdFromUid(uid, (err, accountID) => { + console.log("getOsAccountLocalIdFromUid err: " + JSON.stringify(err)); + console.log('getOsAccountLocalIdFromUid: ' + accountID); + }); + ``` + +### getOsAccountLocalIdFromUid + +getOsAccountLocalIdFromUid(uid: number): Promise<number> + +Obtains the OS account ID based on the process UID. This method uses a promise to return the result. + +- Parameters + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------- | + | uid | number | Yes | Process UID.| + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<number> | Promise used to return the OS account ID obtained.| + +- Example + + Obtain the ID of the OS account whose process UID is **12345678**. + + ``` + const accountManager = account_osAccount.getAccountManager(); + let uid = 12345678; + accountManager.getOsAccountLocalIdFromUid(uid).then((accountID) => { + console.log('getOsAccountLocalIdFromUid: ' + accountID); + }).catch((err) => { + console.log("getOsAccountLocalIdFromUid err: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountLocalIdFromDomain + +getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void + +Obtains the OS account ID based on domain account information. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | --------------------------------------- | + | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | + | callback | AsyncCallback<number> | Yes | Callback used to return the ID of the OS account associated with the domain account.| + +- Example + + ``` + var domainInfo = {domain: "testDomain", accountName: "testAccountName"}; + const accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountLocalIdFromDomain(domainInfo, (err, accountID) => { + console.log("getOsAccountLocalIdFromDomain: " + JSON.stringify(err)); + console.log('getOsAccountLocalIdFromDomain: ' + accountID); + }); + ``` + +### getOsAccountLocalIdFromDomain + +getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> + +Obtains the OS account ID based on domain account information. This method uses a promise to return the result. + +- Parameters + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------- | + | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<number> | Promise used to return the ID of the OS account associated with the domain account.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + var domainInfo = {domain: "testDomain", accountName: "testAccountName"}; + accountManager.getOsAccountLocalIdFromDomain(domainInfo).then((accountID) => { + console.log('getOsAccountLocalIdFromDomain: ' + accountID); + }).catch((err) => { + console.log("getOsAccountLocalIdFromDomain err: " + JSON.stringify(err)); + }); + ``` + +### queryMaxOsAccountNumber + +queryMaxOsAccountNumber(callback: AsyncCallback<number>): void + +Obtains the maximum number of OS accounts that can be created. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ---------------------------------- | + | callback | AsyncCallback<number> | Yes | Callback used to return the maximum number of OS accounts that can be created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryMaxOsAccountNumber((err, maxCnt)=>{ + console.log("queryMaxOsAccountNumber err:" + JSON.stringify(err)); + console.log("queryMaxOsAccountNumber maxCnt:" + maxCnt); + }); + ``` + +### queryMaxOsAccountNumber + +queryMaxOsAccountNumber(): Promise<number> + +Obtains the maximum number of OS accounts that can be created. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<number> | Promise used to return the maximum number of OS accounts that can be created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryMaxOsAccountNumber().then((maxCnt) => { + console.log('queryMaxOsAccountNumber, maxCnt: ' + maxCnt); + }).catch((err) => { + console.log("queryMaxOsAccountNumber err: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountAllConstraints + +getOsAccountAllConstraints(localId: number, callback: AsyncCallback<Array<string>>): void + +Obtains all constraints of an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------- | ---- | ---------------------------------- | + | localId | number | Yes | ID of the target OS account. | + | callback | AsyncCallback<Array<string>> | Yes | Callback used to return all constraints obtained.| + +- Example + + Obtain all constraints of OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.getOsAccountAllConstraints(localId, (err, constraints)=>{ + console.log("getOsAccountAllConstraints err:" + JSON.stringify(err)); + console.log("getOsAccountAllConstraints:" + JSON.stringify(constraints)); + }); + ``` + +### getOsAccountAllConstraints + +getOsAccountAllConstraints(localId: number): Promise<Array<string>> + +Obtains all constraints of an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | Yes | ID of the target OS account.| + +- Return value + + | Type | Description | + | :--------------------- | :---------------------------------- | + | Promise<Array<string>> | Promise used to return the constraints obtained.| + +- Example + + Obtain all constraints of OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.getOsAccountAllConstraints(localId).then((constraints) => { + console.log("getOsAccountAllConstraints, constraints: " + constraints); + }).catch((err) => { + console.log("getOsAccountAllConstraints err: " + JSON.stringify(err)); + }); + ``` + +### queryAllCreatedOsAccounts + +queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>>): void + +Obtains information about all the OS accounts created. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------- | ---- | -------------------------------- | + | callback | AsyncCallback<Array<[OsAccountInfo](#osaccountinfo)>> | Yes | Callback used to return information about OS accounts created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryAllCreatedOsAccounts((err, accountArr)=>{ + console.log("queryAllCreatedOsAccounts err:" + JSON.stringify(err)); + console.log("queryAllCreatedOsAccounts accountArr:" + JSON.stringify(accountArr)); + }); + ``` + +### queryAllCreatedOsAccounts + +queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> + +Obtains information about all the OS accounts created. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :---------------------------- | :---------------------------------- | + | Promise<Array<[OsAccountInfo](#osaccountinfo)>> | Promise used to return information about OS accounts created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryAllCreatedOsAccounts().then((accountArr) => { + console.log('queryAllCreatedOsAccounts, accountArr: ' + JSON.stringify(accountArr)); + }).catch((err) => { + console.log("queryAllCreatedOsAccounts err: " + JSON.stringify(err)); + }); + ``` + +### queryActivatedOsAccountIds + +queryActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void + +Obtains information about all activated OS accounts. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------- | ---- | -------------------------------- | + | callback | AsyncCallback<Array<number>> | Yes | Callback used to return information about activated OS accounts.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryActivatedOsAccountIds((err, idArray)=>{ + console.log("queryActivatedOsAccountIds err:" + JSON.stringify(err)); + console.log("queryActivatedOsAccountIds idArray length:" + idArray.length); + for(var i=0;i { + console.log('queryActivatedOsAccountIds, idArray: ' + idArray); + }).catch((err) => { + console.log("queryActivatedOsAccountIds err: " + JSON.stringify(err)); + }); + ``` + +### createOsAccount + +createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback<OsAccountInfo>): void + +Creates an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | :-------- | ---------------------------- | ---- | -------------------- | + | localName | string | Yes | Name of the OS account to create. | + | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | + | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.createOsAccount("testName", osaccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + console.log("createOsAccount err:" + JSON.stringify(err)); + console.log("createOsAccount osAccountInfo:" + JSON.stringify(osAccountInfo)); + }); + ``` + +### createOsAccount + +createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInfo> + +Creates an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | --------- | ------------- | ---- | ---------------- | + | localName | string | Yes | Name of the OS account to create.| + | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| + +- Return value + + | Type | Description | + | :--------------------- | :---------------------------------- | + | Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.createOsAccount("testAccountName", osaccount.OsAccountType.NORMAL).then((accountInfo) => { + console.log("createOsAccount, accountInfo: " + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log("createOsAccount err: " + JSON.stringify(err)); + }); + ``` + +### createOsAccountForDomain + +createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>): void + +Creates an OS account and associates it with the specified domain account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | :-------- | ---------------------------- | ---- | -------------------- | + | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | + | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | + | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + var domainInfo = {domain: "testDomain", accountName: "testAccountName"}; + accountManager.createOsAccountForDomain(osaccount.OsAccountType.NORMAL, domainInfo, (err, osAccountInfo)=>{ + console.log("createOsAccountForDomain err:" + JSON.stringify(err)); + console.log("createOsAccountForDomain osAccountInfo:" + JSON.stringify(osAccountInfo)); + }); + ``` + +### createOsAccountForDomain + +createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo> + +Creates an OS account and associates it with the specified domain account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | --------- | ------------- | ---- | ---------------- | + | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| + | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| + +- Return value + + | Type | Description | + | :--------------------- | :---------------------------------- | + | Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account created.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + var domainInfo = {domain: "testDomain", accountName: "testAccountName"}; + accountManager.createOsAccountForDomain(osaccount.OsAccountType.NORMAL, domainInfo).then((accountInfo) => { + console.log("createOsAccountForDomain, account info: " + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log("createOsAccountForDomain err: " + JSON.stringify(err)); + }); + ``` + +### queryCurrentOsAccount + +queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void + +Obtains information about the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------- | ---- | -------------------------- | + | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return information about the OS account obtained.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryCurrentOsAccount((err, curAccountInfo)=>{ + console.log("queryCurrentOsAccount err:" + JSON.stringify(err)); + console.log("queryCurrentOsAccount curAccountInfo:" + JSON.stringify(curAccountInfo)); + }); + ``` + +### queryCurrentOsAccount + +queryCurrentOsAccount(): Promise<OsAccountInfo> + +Obtains information about the OS account to which the current process belongs. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :--------------------- | :---------------------------------- | + | Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return information about the OS account obtained.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryCurrentOsAccount().then((accountInfo) => { + console.log("queryCurrentOsAccount, accountInfo: " + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log("queryCurrentOsAccount err: " + JSON.stringify(err)); + }); + ``` + +### queryOsAccountById + +queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo>): void + +Obtains information about an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------- | ---- | -------------------------- | + | localId | number | Yes | ID of the target OS account.| + | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account information obtained.| + +- Example + + Query information about OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.queryOsAccountById(localId, (err, accountInfo)=>{ + console.log("queryOsAccountById err:" + JSON.stringify(err)); + console.log("queryOsAccountById accountInfo:" + JSON.stringify(accountInfo)); + }); + ``` + +### queryOsAccountById + +queryOsAccountById(localId: number): Promise<OsAccountInfo> + +Obtains information about an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------- | ---- | -------------------------- | + | localId | number | Yes | ID of the target OS account.| + +- Return value + + | Type | Description | + | :--------------------- | :---------------------------------- | + | Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account information obtained.| + +- Example + + Query information about OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.queryOsAccountById(localId).then((accountInfo) => { + console.log("queryOsAccountById, accountInfo: " + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log("queryOsAccountById err: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountTypeFromProcess + +getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void + +Obtains the type of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------- | ---- | ---------------------------------------- | + | callback | AsyncCallback<[OsAccountType](#osaccounttype)> | Yes | Callback used to return the OS account type.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountTypeFromProcess((err, accountType) => { + console.log("getOsAccountTypeFromProcess err: " + JSON.stringify(err)); + console.log('getOsAccountTypeFromProcess accountType: ' + accountType); + }); + ``` + +### getOsAccountTypeFromProcess + +getOsAccountTypeFromProcess(): Promise<OsAccountType> + +Obtains the type of the OS account to which the current process belongs. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :--------------------- | :---------------------------------- | + | Promise<[OsAccountType](#osaccounttype)> | Promise used to return the OS account type.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountTypeFromProcess().then((accountType) => { + console.log('getOsAccountTypeFromProcess, accountType: ' + accountType); + }).catch((err) => { + console.log("getOsAccountTypeFromProcess err: " + JSON.stringify(err)); + }); + ``` + +### getDistributedVirtualDeviceId + +getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void + +Obtains the ID of this distributed virtual device. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ---------------------------- | + | callback | AsyncCallback<string> | Yes | Callback used to return the device ID obtained.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getDistributedVirtualDeviceId((err, virtualID) => { + console.log("getDistributedVirtualDeviceId err: " + JSON.stringify(err)); + console.log('getDistributedVirtualDeviceId virtualID: ' + virtualID); + }); + ``` + +### getDistributedVirtualDeviceId + +getDistributedVirtualDeviceId(): Promise<string> + +Obtains the ID of this distributed virtual device. This method uses a promise to return the result. + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<string> | Promise used to return the device ID obtained.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + accountManager.getDistributedVirtualDeviceId().then((virtualID) => { + console.log('getDistributedVirtualDeviceId, virtualID: ' + virtualID); + }).catch((err) => { + console.log("getDistributedVirtualDeviceId err: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountProfilePhoto + +getOsAccountProfilePhoto(localId: number, callback: AsyncCallback<string>): void + +Obtains the profile photo of an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ------------------------ | + | localId | number | Yes | ID of the target OS account. | + | callback | AsyncCallback<string> | Yes | Callback used to return the profile photo obtained.| + +- Example + + Obtain the profile photo of OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.getOsAccountProfilePhoto(localId, (err, photo)=>{ + console.log("getOsAccountProfilePhoto err:" + JSON.stringify(err)); + console.log("get photo:" + photo + " by localId: " + localId); + }); + ``` + +### getOsAccountProfilePhoto + +getOsAccountProfilePhoto(localId: number): Promise<string> + +Obtains the profile photo of an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | Yes | ID of the target OS account.| + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<string> | Promise used to return the profile photo obtained.| + +- Example + + Obtain the profile photo of OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.getOsAccountProfilePhoto(localId).then((photo) => { + console.log("getOsAccountProfilePhoto: " + photo); + }).catch((err) => { + console.log("getOsAccountProfilePhoto err: " + JSON.stringify(err)); + }); + ``` + +### setOsAccountProfilePhoto + +setOsAccountProfilePhoto(localId: number, photo: string, callback: AsyncCallback<void>): void + +Sets a profile photo for an OS account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------- | ---- | ------------------------ | + | localId | number | Yes | ID of the target OS account. | + | photo | string | Yes | Profile photo information. | + | callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +- Example + + Set a profile photo for OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + var photo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPCAYAAAA/I0V3AAAAAXNSR0IArs4c6QAAAARnQU1BAA"+ + "Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y"+ + "q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo"+ + "+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==" + osAccountManager.setOsAccountProfilePhoto(localId, photo, (err)=>{ + console.log("setOsAccountProfilePhoto err:" + JSON.stringify(err)); + }); + ``` + +### setOsAccountProfilePhoto + +setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> + +Sets a profile photo for an OS account. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | Yes | ID of the target OS account.| + | photo | string | Yes | Profile photo information. | + +- Return value + + | Type | Description | + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + Set a profile photo for OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + var photo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPCAYAAAA/I0V3AAAAAXNSR0IArs4c6QAAAARnQU1BAA"+ + "Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y"+ + "q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo"+ + "+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==" + accountManager.setOsAccountProfilePhoto(localId, photo).then(() => { + console.log("setOsAccountProfilePhoto success"); + }).catch((err) => { + console.log("setOsAccountProfilePhoto err: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountLocalIdBySerialNumber + +getOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void + +Obtains the OS account ID based on the SN. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------------ | --------------------- | ---- | ------------------------------ | + | serialNumber | number | Yes | Account SN. | + | callback | AsyncCallback<number> | Yes | Callback used to return the OS account ID obtained.| + +- Example + + Obtain the ID of the OS account whose SN is 12345. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var serialNumber = 12345; + accountManager.getOsAccountLocalIdBySerialNumber(serialNumber, (err, localId)=>{ + console.log("ger localId err:" + JSON.stringify(err)); + console.log("get localId:" + localId + " by serialNumber: " + serialNumber); + }); + ``` + +### getOsAccountLocalIdBySerialNumber + +getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> + +Obtains the OS account ID based on the SN. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------------ | ------ | ---- | ---------- | + | serialNumber | number | Yes | Account SN.| + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<number> | Promise used to return the OS account ID obtained.| + +- Example + + Obtain the ID of the OS account whose SN is 12345. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var serialNumber = 12345; + accountManager.getOsAccountLocalIdBySerialNumber(serialNumber).then((localId) => { + console.log("getOsAccountLocalIdBySerialNumber localId: " + localId); + }).catch((err) => { + console.log("getOsAccountLocalIdBySerialNumber err: " + JSON.stringify(err)); + }); + ``` + +### getSerialNumberByOsAccountLocalId + +getSerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void + +Obtains the SN of an OS account based on the account ID. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ------------------------------ | + | localId | number | Yes | ID of the target OS account. | + | callback | AsyncCallback<number> | Yes | Callback used to return the account SN obtained.| + +- Example + + Obtain the SN of the OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.getSerialNumberByOsAccountLocalId(localId, (err, serialNumber)=>{ + console.log("ger serialNumber err:" + JSON.stringify(err)); + console.log("get serialNumber:" + serialNumber + " by localId: " + localId); + }); + ``` + +### getSerialNumberByOsAccountLocalId + +getSerialNumberByOsAccountLocalId(localId: number): Promise<number> + +Obtains the SN of an OS account based on the account ID. This method uses a promise to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------ | + | localId | number | Yes | ID of the target OS account.| + +- Return value + + | Type | Description | + | :-------------- | :---------------------------------- | + | Promise<number> | Promise used to return the account SN obtained.| + +- Example + + Obtain the SN of the OS account 100. + + ``` + const accountManager = account_osAccount.getAccountManager(); + var localId = 100; + accountManager.getSerialNumberByOsAccountLocalId(localId).then((serialNumber) => { + console.log("getSerialNumberByOsAccountLocalId serialNumber: " + serialNumber); + }).catch((err) => { + console.log("getSerialNumberByOsAccountLocalId err: " + JSON.stringify(err)); + }); + ``` + +### on + +on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void + +Subscribes to OS account changes. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------------- | ---- | ------------------------ | + | type | 'activate' \| 'activating' | Yes | Type of the event to subscribe to. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated. | + | name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes.| + | callback | Callback<number> | Yes | Callback used to return the OS account ID and status changes.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + function onCallback(receiveLocalId){ + console.log("receive localId:" + receiveLocalId); + } + accountManager.on("activating", "osAccountOnOffNameA", onCallback); + ``` + +### off + +off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void + +Unsubscribes from the OS account changes. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------------- | ---- | ---------------------------- | + | type | 'activate' \| 'activating' | Yes | Type of the event to unsubscribe from. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated. | + | name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes, and must be the same as the value passed by **on()**.| + | callback | Callback<number> | No | Callback used to return the OS account changes. By default, **0** is returned.| + +- Example + + ``` + const accountManager = account_osAccount.getAccountManager(); + function offCallback(){ + console.log("off enter") + } + accountManager.off("activating", "osAccountOnOffNameA", offCallback); + ``` + +## OsAccountInfo +Defines information about an OS account. +| Name | Type | Mandatory| Description | +| ----------------- | ---------------------------------- | ---- | ------------------------ | +| localId | number | Yes | ID of the target OS account. | +| localName | string | Yes | OS account name. | +| type | [OsAccountType](#osaccounttype) | Yes | OS account type. | +| [constraints](constraints) | Array<string> | No | Constraints on the OS account. | +| isVerified | boolean | Yes | Whether the OS account is verified. | +| photo | string | No | Profile photo of the OS account. | +| createTime | number | Yes | Time when the OS account was created. | +| lastLoginTime | number | No | Last login time of the OS account.| +| serialNumber | number | Yes | SN of the OS account. | +| isActived | boolean | Yes | Whether the OS account is activated. | +| isCreateCompleted | boolean | Yes | Whether the OS account information is complete. | +| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. | + +## DomainAccountInfo +Defines the domain account information. +| Name | Type | Mandatory| Description | +| ----------------- | ---------------------------------- | ---- | ------------------------ | +| domain | string | Yes | Domain name. | +| accountName | string | Yes | Domain account name. | + +## Constraints + +| Constraint| Description| +| ----------------- | ------------------- | +| constraint.wifi | A user is not allowed to use Wi-Fi.| +| constraint.wifi.set | A user is not allowed to change Wi-Fi settings.| +| constraint.locale.set | A user is not allowed to change the device language.| +| constraint.app.accounts | A user is not allowed to add or delete app accounts.| +| constraint.apps.install | A user is not allowed to install apps.| +| constraint.apps.uninstall | A user is not allowed to uninstall apps.| +| constraint.location.shared | A user is not allowed to enable location sharing.| +| constraint.unknown.sources.install | A user is not allowed to install apps from unknown sources.| +| constraint.global.unknown.app.install | All users are not allowed to install apps from unknown sources.| +| constraint.bluetooth.set | A user is not allowed to configure Bluetooth.| +| constraint.bluetooth | The use of Bluetooth is prohibited on the device. +| constraint.bluetooth.share | Bluetooth sharing is prohibited.| +| constraint.usb.file.transfer | A user is not allowed to transfer files over USB.| +| constraint.credentials.set | A user is not allowed to configure user credentials.| +| constraint.os.account.remove | An admin user is not allowed to remove users or a non-admin user is not allowed to remove itself.| +| constraint.managed.profile.remove | The managed profiles of this user cannot be removed.| +| constraint.debug.features.use | A user is not allowed to enable or access debugging features.| +| constraint.vpn.set | A user is not allowed to configure a VPN.| +| constraint.date.time.set | A user is not allowed to set date, time, or time zone.| +| constraint.tethering.config | A user is not allowed to configure Tethering.| +| constraint.network.reset | A user is not allowed to reset network settings.| +| constraint.factory.reset | A user is not allowed to reset factory settings.| +| constraint.os.account.create | A user is not allowed to create users.| +| constraint.add.managed.profile | A user is not allowed to add managed profiles.| +| constraint.apps.verify.disable | A user is not allowed to disable app verification.| +| constraint.cell.broadcasts.set | A user is not allowed to configure cell broadcasts.| +| constraint.mobile.networks.set | A user is not allowed to configure radio networks.| +| constraint.control.apps | A user is not allowed to modify apps in **Settings** or the boot module.| +| constraint.physical.media | A user is not allowed to mount external physical media.| +| constraint.microphone | A user is not allowed to use microphones.| +| constraint.microphone.unmute | A user is not allowed to adjust the microphone volume.| +| constraint.volume.adjust | A user is not allowed to adjust the device's global volume.| +| constraint.calls.outgoing | A user is not allowed to make outgoing calls.| +| constraint.sms.use | A user is not allowed to send or receive SMS messages.| +| constraint.fun | A user is not allowed to have entertainment.| +| constraint.windows.create | Windows other than app windows cannot be created.| +| constraint.system.error.dialogs | Error dialogs for crashed or unresponsive apps are prohibited.| +| constraint.cross.profile.copy.paste | Pasting clipboard content to other users or profiles is prohibited.| +| constraint.beam.outgoing | A user is not allowed to use Near Field Communications (NFC) to transfer data from apps.| +| constraint.wallpaper | A user is not allowed to manage wallpapers.| +| constraint.safe.boot | A user is not allowed to reboot the device in safe boot mode.| +| constraint.parent.profile.app.linking | The apps in the parent profile are allowed to handle web links from the managed profile.| +| constraint.audio.record | Audio recording is prohibited.| +| constraint.camera.use | The use of cameras is prohibited.| +| constraint.os.account.background.run | Running in the background is prohibited.| +| constraint.data.roam | A user is not allowed to use cellular data when roaming.| +| constraint.os.account.set.icon | A user is not allowed to change their icon.| +| constraint.wallpaper.set | A user is not allowed to set a wallpaper.| +| constraint.oem.unlock | A user is not allowed to enable OEM unlock.| +| constraint.device.unmute | A user is not allowed to mute the device's global volume.| +| constraint.password.unified | The managed profile is not allowed to have unified lock screen challenge with the primary user.| +| constraint.autofill | A user is not allowed to use the autofill service.| +| constraint.content.capture | Capturing the content of a user's screen is prohibited.| +| constraint.content.suggestions | A user is not allowed to receive content suggestions.| +| constraint.os.account.start | User switching is blocked.| +| constraint.location.set | A user is not allowed to configure the location service.| +| constraint.airplane.mode.set | The airplane mode is prohibited on the device.| +| constraint.brightness.set | A user is not allowed to configure brightness.| +| constraint.share.into.profile | A user is not allowed to share files, images, or data from the primary user to the managed profile.| +| constraint.ambient.display | Ambient display is prohibited for the user.| +| constraint.screen.timeout.set | A user is not allowed to configure the screen off timeout.| +| constraint.print | A user is not allowed to print.| +| constraint.private.dns.set | A user is not allowed to configure a private domain name server (DNS).| diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 58e1d756d0171187c7f8c388dfe22d9757554563..80b633d92c2e0db156c98ea5a5b577fd1078ebdb 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -10,7 +10,7 @@ import PlainArray from '@ohos.util.PlainArray' ``` -## System Capabilities +## System Capability SystemCapability.Utils.Lang @@ -432,7 +432,7 @@ callbackfn | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the entry that is currently traversed.| | key | number | Yes| Key of the entry that is currently traversed.| -| plainArray | PlainArray | No| Instance that invokes the **forEach** method.| +| plainArray | PlainArray | No| Instance that invokes the **forEach** API.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index fa563d5a494b2c370950822e27c6397372f53669..01308446e852763d8d4846fb6d9e6d12ea42a69a 100644 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -262,7 +262,7 @@ var pres = process.getThreadPriority(tid); ## process.getStartRealtime8+ -getStartRealtime() :number +getStartRealtime(): number Obtains the duration, in milliseconds, from the time the system starts to the time the process starts. @@ -280,7 +280,7 @@ var realtime = process.getStartRealtime(); ## process.getPastCputime8+ -getPastCputime() :number +getPastCputime(): number Obtains the CPU time (in milliseconds) from the time the process starts to the current time. diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 8b9cf97f184547b9f5ce59da96bf85a6021bee55..b163b58eb419404541c7e570ef349579d53729eb 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -10,43 +10,28 @@ import sensor from '@ohos.sensor'; ``` -## System Capabilities -SystemCapability.Sensors.Sensor +## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) -## Required Permissions +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void -To use the pedometer sensor, you must declare the **ohos.permission.ACTIVITY_MOTION** permission. - -To use the heart rate sensor, you must declare the **ohos.permission.READ_HEALTH_DATA** permission. - -To use the acceleration sensor, you must declare the **ohos.permission.ACCELEROMETER** permission. - -To use the gyroscope sensor, you must declare the **ohos.permission.GYROSCOPE** permission. - - -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER) - -on(type: sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<AccelerometerResponse>,options?: Options): void +Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) -Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| - | callback | AsyncCallback<[AccelerometerResponse](#accelerometerresponse)> | Yes| Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| + | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes| Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -56,26 +41,26 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +## sensor.on(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) -on(type:sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback<LinearAccelerometerResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| - | callback | AsyncCallback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes| Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| + | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes| Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -85,26 +70,26 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) -on(type:sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback<AccelerometerUncalibratedResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void Subscribes to data changes of the uncalibrated acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| - | callback | AsyncCallback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes| Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| + | callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes| Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -117,26 +102,24 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY) +## sensor.on(SensorType.SENSOR_TYPE_ID_GRAVITY) -on(type: sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<GravityResponse>,options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void Subscribes to data changes of the gravity sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**.| - | callback | AsyncCallback<[GravityResponse](#gravityresponse)> | Yes| Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| + | callback | Callback<[GravityResponse](#gravityresponse)> | Yes| Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -146,26 +129,26 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE) +## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE) -on(type: sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<GyroscopeResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void Subscribes to data changes of the gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. +**Required permissions**: ohos.permission.GYROSCOPE (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**.| - | callback | AsyncCallback<[GyroscopeResponse](#gyroscoperesponse)> | Yes| Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| + | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes| Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -175,26 +158,26 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) -on(type:sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback<GyroscopeUncalibratedResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. +**Required permissions**: ohos.permission.GYROSCOPE (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| - | callback | AsyncCallback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes| Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| + | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes| Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -207,26 +190,24 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +## sensor.on(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) -on(type: sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: AsyncCallback<SignificantMotionResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void Subscribes to data changes of the significant motion sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| - | callback | AsyncCallback<[SignificantMotionResponse](#significantmotionresponse)> | Yes| Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| + | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes| Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ console.info('Scalar data: ' + data.scalar); }, {interval: 10000000} @@ -234,26 +215,26 @@ Subscribes to data changes of the significant motion sensor. If this API is call ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) -on(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: AsyncCallback<PedometerDetectResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void Subscribes to data changes of the pedometer detection sensor. If this API is called multiple times for the same application, the last call takes effect. +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| - | callback | AsyncCallback<[PedometerDetectResponse](#pedometerdetectresponse)> | Yes| Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectResponse**.| + | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes| Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ console.info('Scalar data: ' + data.scalar); }, {interval: 10000000} @@ -261,26 +242,26 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER) +## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER) -on(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<PedometerResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void Subscribes to data changes of the pedometer sensor. If this API is called multiple times for the same application, the last call takes effect. +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**.| - | callback | AsyncCallback<[PedometerResponse](#pedometerresponse)> | Yes| Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| + | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes| Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ console.info('Steps: ' + data.steps); }, {interval: 10000000} @@ -288,26 +269,24 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) -on(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback<AmbientTemperatureResponse>, options?: Options): void +on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void Subscribes to data changes of the ambient temperature sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| - | callback | AsyncCallback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes| Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| + | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes| Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ console.info('Temperature: ' + data.temperature); }, {interval: 10000000} @@ -315,26 +294,24 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) -on(type: sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<MagneticFieldResponse>,options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void Subscribes to data changes of the magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| - | callback | AsyncCallback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes| Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| + | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes| Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -344,26 +321,24 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) -on(type:sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback<MagneticFieldUncalibratedResponse>, options: Options): void +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options: Options): void Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| - | callback | AsyncCallback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes| Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| + | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes| Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -376,26 +351,24 @@ Subscribes to data changes of the uncalibrated magnetic field sensor. If this AP ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY) +## sensor.on(SensorType.SENSOR_TYPE_ID_PROXIMITY) -on(type:sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<ProximityResponse>,options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**.| - | callback | AsyncCallback<[ProximityResponse](#proximityresponse)> | Yes| Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| + | callback | Callback<[ProximityResponse](#proximityresponse)> | Yes| Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ console.info('Distance: ' + data.distance); }, {interval: 10000000} @@ -403,26 +376,24 @@ Subscribes to data changes of the proximity sensor. If this API is called multip ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY) +## sensor.on(SensorType.SENSOR_TYPE_ID_HUMIDITY) -on(type: sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<HumidityResponse>,options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void Subscribes to data changes of the humidity sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**.| - | callback | AsyncCallback<[HumidityResponse](#humidityresponse)> | Yes| Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| + | callback | Callback<[HumidityResponse](#humidityresponse)> | Yes| Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ console.info('Humidity: ' + data.humidity); }, {interval: 10000000} @@ -430,26 +401,24 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER) +## sensor.on(SensorType.SENSOR_TYPE_ID_BAROMETER) -on(type:sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<BarometerResponse>,options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**.| - | callback | AsyncCallback<[BarometerResponse](#barometerresponse)> | Yes| Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| + | callback | Callback<[BarometerResponse](#barometerresponse)> | Yes| Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ console.info('Atmospheric pressure: ' + data.pressure); }, {interval: 10000000} @@ -457,26 +426,24 @@ Subscribes to data changes of the barometer sensor. If this API is called multip ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL) +## sensor.on(SensorType.SENSOR_TYPE_ID_HALL) -on(type: sensor.SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void Subscribes to data changes of the Hall effect sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**.| - | callback | AsyncCallback<[HallResponse](#hallresponse)> | Yes| Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| + | callback | Callback<[HallResponse](#hallresponse)> | Yes| Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ console.info('Status: ' + data.status); }, {interval: 10000000} @@ -484,26 +451,24 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) -on(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<LightResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void Subscribes to data changes of the ambient light sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| - | callback | AsyncCallback<[LightResponse](#lightresponse)> | Yes| Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + | callback | Callback<[LightResponse](#lightresponse)> | Yes| Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ console.info(' Illumination: ' + data.intensity); }, {interval: 10000000} @@ -511,84 +476,105 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION) +## sensor.on(SensorType.SENSOR_TYPE_ID_ORIENTATION) -on(type: sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<OrientationResponse>, options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void Subscribes to data changes of the orientation sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**.| - | callback | AsyncCallback<[OrientationResponse](#orientationresponse)> | Yes| Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| + | callback | Callback<[OrientationResponse](#orientationresponse)> | Yes| Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); }, {interval: 10000000} ); ``` +## sensor.on(SensorType.SENSOR_TYPE_ID_HEART_RATE) + +on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void + +Subscribes to only one data change of the heart rate sensor. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| + +- Example -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +``` +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ + console.info("Heart rate: " + data.heartRate); +}, + {interval: 10000000} +); +``` -on(type:sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback<RotationVectorResponse>,options?: Options): void +## sensor.on(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) + +on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void Subscribes to data changes of the rotation vector sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| - | callback | AsyncCallback<[RotationVectorResponse](#rotationvectorresponse)> | Yes| Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| + | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes| Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); }, {interval: 10000000} ); ``` -## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +## sensor.on(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) -on(type: sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback<WearDetectionResponse>,options?: Options): void +on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void Subscribes to data changes of the wear detection sensor. If this API is called multiple times for the same application, the last call takes effect. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| - | callback | AsyncCallback<[WearDetectionResponse](#weardetectionresponse)> | Yes| Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes| Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| - Example ``` - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); }, {interval: 10000000} @@ -596,25 +582,25 @@ Subscribes to data changes of the wear detection sensor. If this API is called m ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) -once(type: sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<AccelerometerResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void Subscribes to only one data change of the acceleration sensor. +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| - | callback | AsyncCallback<[AccelerometerResponse](#accelerometerresponse)> | Yes| One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| + | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes| One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(error,data){ - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -623,25 +609,25 @@ Subscribes to only one data change of the acceleration sensor. ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +## sensor.once(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) -once(type:sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback<LinearAccelerometerResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void Subscribes to only one data change of the linear acceleration sensor. +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| - | callback | AsyncCallback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes| One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| + | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes| One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -650,25 +636,25 @@ Subscribes to only one data change of the linear acceleration sensor. ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) -once(type:sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback<AccelerometerUncalibratedResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void Subscribes to only one data change of the uncalibrated acceleration sensor. +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| - | callback | AsyncCallback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| + | callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -680,25 +666,23 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY) +## sensor.once(SensorType.SENSOR_TYPE_ID_GRAVITY) -once(type:sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<GravityResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void Subscribes to only one data change of the gravity sensor. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**.| - | callback | AsyncCallback<[GravityResponse](#gravityresponse)> | Yes| One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| + | callback | Callback<[GravityResponse](#gravityresponse)> | Yes| One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -707,25 +691,25 @@ Subscribes to only one data change of the gravity sensor. ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE) +## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE) -once(type: sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<GyroscopeResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void Subscribes to only one data change of the gyroscope sensor. +**Required permissions**: ohos.permission.GYROSCOPE (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**.| - | callback | AsyncCallback<[GyroscopeResponse](#gyroscoperesponse)> | Yes| One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| + | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes| One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -734,25 +718,25 @@ Subscribes to only one data change of the gyroscope sensor. ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) -once(type:sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback<GyroscopeUncalibratedResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void Subscribes to only one data change of the uncalibrated gyroscope sensor. +**Required permissions**: ohos.permission.GYROSCOPE (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| - | callback | AsyncCallback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| + | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -764,125 +748,119 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +## sensor.once(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) -once(type: sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback<SignificantMotionResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void Subscribes to only one data change of the significant motion sensor. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| - | callback | AsyncCallback<[SignificantMotionResponse](#significantmotionresponse)> | Yes| One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| + | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes| One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) -once(type:sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback<PedometerDetectResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void Subscribes to only one data change of the pedometer detection sensor. +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| - | callback | AsyncCallback<[PedometerDetectResponse](#pedometerdetectresponse)> | Yes| One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectResponse**.| + | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes| One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER) +## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER) -once(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<PedometerResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void Subscribes to only one data change of the pedometer sensor. +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**.| - | callback | AsyncCallback<[PedometerResponse](#pedometerresponse)> | Yes| One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| + | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes| One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { console.info('Steps: ' + data.steps); } ); ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) -once(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback<AmbientTemperatureResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void Subscribes to only one data change of the ambient temperature sensor. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| - | callback | AsyncCallback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes| One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| + | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes| One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { console.info('Temperature: ' + data.temperature); } ); ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) -once(type: sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<MagneticFieldResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void Subscribes to only one data change of the magnetic field sensor. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| - | callback | AsyncCallback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes| One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| + | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes| One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -891,302 +869,815 @@ Subscribes to only one data change of the magnetic field sensor. ``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) -once(type:sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback<MagneticFieldUncalibratedResponse>): void +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void Subscribes to only one data change of the uncalibrated magnetic field sensor. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| - | callback | AsyncCallback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| + | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| - Example ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_PROXIMITY) + +once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void + +Subscribes to only one data change of the proximity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**.| + | callback | Callback<[ProximityResponse](#proximityresponse)> | Yes| One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } + console.info('Distance: ' + data.distance); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_HUMIDITY) + +once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void + +Subscribes to only one data change of the humidity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**.| + | callback | Callback<[HumidityResponse](#humidityresponse)> | Yes| One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { + console.info('Humidity: ' + data.humidity); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_BAROMETER) + +once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void + +Subscribes to only one data change of the barometer sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**.| + | callback | Callback<[BarometerResponse](#barometerresponse)> | Yes| One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_HALL) + +once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void + +Subscribes to only one data change of the Hall effect sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**.| + | callback | Callback<[HallResponse](#hallresponse)> | Yes| One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { + console.info('Status: ' + data.status); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) + +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void + +Subscribes to only one data change of the ambient light sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| + | callback | Callback<[LightResponse](#lightresponse)> | Yes| One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { + console.info(' Illumination: ' + data.intensity); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_ORIENTATION) + +once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void + +Subscribes to only one data change of the orientation sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**.| + | callback | Callback<[OrientationResponse](#orientationresponse)> | Yes| One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) + +once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void + +Subscribes to only one data change of the rotation vector sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| + | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes| One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); + console.info('Scalar quantity: ' + data.w); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_HEART_RATE) + +once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void + +Subscribes to only one data change of the heart rate sensor. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**.| + | callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes| One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { + console.info("Heart rate: " + data.heartRate); + } + ); + ``` + + +## sensor.once(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) + +once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void + +Subscribes to only one data change of the wear detection sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| + | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes| One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + +- Example + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { + console.info("Wear status: "+ data.value); } ); ``` +## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| + +- Example + +``` +function callback(data) { + console.info('x-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| + +- Example + +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void + +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + +- Example + +``` +function callback(data) { + console.info(' Illumination: ' + data.intensity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void + +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| + +- Example + +``` +function callback(data) { + console.info('Temperature: ' + data.temperature); +} +sensor.off( sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) + +off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void + +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| + +- Example + +``` +function callback(data) { + console.info('Atmospheric pressure: ' + data.pressure); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_GRAVITY) + +off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void + +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| + +- Example + +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.GYROSCOPE (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| + +- Example + +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.GYROSCOPE (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| + +- Example + +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_HALL) + +off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void + +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| + +- Example + +``` +function callback(data) { + console.info('Status: ' + data.status); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_HEART_RATE) + +off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| + +- Example + +``` +function callback(data) { + console.info("Heart rate: " + data.heartRate); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_HUMIDITY) + +off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void + +Unsubscribes from sensor data changes. + +**Required permission**: ohos.permission.READ_HEALTH_DATA (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| + +- Example + +``` +function callback(data) { + console.info('Humidity: ' + data.humidity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY) +off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void -once(type: sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<ProximityResponse>): void +Unsubscribes from sensor data changes. -Subscribes to only one data change of the proximity sensor. +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**.| - | callback | AsyncCallback<[ProximityResponse](#proximityresponse)> | Yes| One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info('Distance: ' + data.distance); - } - ); - ``` +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); +``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY) +## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) -once(type: sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<HumidityResponse>): void + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void -Subscribes to only one data change of the humidity sensor. +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**.| - | callback | AsyncCallback<[HumidityResponse](#humidityresponse)> | Yes| One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| + +| Name | Type | Mandatory| Description | +| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info('Humidity: ' + data.humidity); - } - ); - ``` +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); +``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER) +## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) -once(type: sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<BarometerResponse>): void + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void -Subscribes to only one data change of the barometer sensor. +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**.| - | callback | AsyncCallback<[BarometerResponse](#barometerresponse)> | Yes| One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info('Atmospheric pressure: ' + data.pressure); - } - ); - ``` +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_ORIENTATION) -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL) + off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void -once(type: sensor.SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResponse>): void +Unsubscribes from sensor data changes. -Subscribes to only one data change of the Hall effect sensor. +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**.| - | callback | AsyncCallback<[HallResponse](#hallresponse)> | Yes| One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info('Status: ' + data.status); - } - ); - ``` +``` +function callback(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); +``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER) -once(type: sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<LightResponse>): void +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void -Subscribes to only one data change of the ambient light sensor. +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| - | callback | AsyncCallback<[LightResponse](#lightresponse)> | Yes| One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info(' Illumination: ' + data.intensity); - } - ); - ``` +``` +function callback(data) { + console.info('Steps: ' + data.steps); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) + +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION) +Unsubscribes from sensor data changes. -once(type: sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<OrientationResponse>): void +**Required permissions**: ohos.permission.ACTIVITY_MOTION -Subscribes to only one data change of the orientation sensor. +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**.| - | callback | AsyncCallback<[OrientationResponse](#orientationresponse)> | Yes| One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` +``` +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_PROXIMITY) -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void -once(type: sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback<RotationVectorResponse>): void +Unsubscribes from sensor data changes. -Subscribes to only one data change of the rotation vector sensor. +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| - | callback | AsyncCallback<[RotationVectorResponse](#rotationvectorresponse)> | Yes| One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` +``` +function callback(data) { + console.info('Distance: ' + data.distance); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); +``` + +## sensor.off(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE) +off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void -once(type: sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback<HeartRateResponse>): void +Unsubscribes from sensor data changes. -Subscribes to only one data change of the heart rate sensor. +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**.| - | callback | AsyncCallback<[HeartRateResponse](#heartrateresponse)> | Yes| One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info("Heart rate: " + data.heartRate); - } - ); - ``` +``` +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); +``` -## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +## sensor.off(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) -once(type: sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback<WearDetectionResponse>): void +off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void -Subscribes to only one data change of the wear detection sensor. +Unsubscribes from sensor data changes. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| - | callback | AsyncCallback<[WearDetectionResponse](#weardetectionresponse)> | Yes| One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| - Example - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(error, data) { - if (error) { - console.error("Failed to register data, error code is" + error.code + ", message: " + error.message); - return; - } - console.info("Wear status: "+ data.value); - } - ); - ``` +``` +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); +``` -## sensor.off +## sensor.off(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) -off(type: SensorType, callback?: AsyncCallback<void>): void +off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void Unsubscribes from sensor data changes. +**System capability**: SystemCapability.Sensors.Sensor + - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to unsubscribe from.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| - Example - ``` - sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error) { - if (error) { - console.error("Failed to unsubscribe from acceleration sensor data. Error code: " + error.code + "; message: " + error.message); - return; - } - console.info("Succeeded in unsubscribing from acceleration sensor data."); - } - ); - ``` + +``` +function accCallback(data) { + console.info('Wear status: ' + data.value); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); +``` ## sensor.transformCoordinateSystem transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void -Rotates a rotation vector so that it can represent the coordinate system in different ways. This method uses a callback to return the result. +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | ---------------- | ----------------------------------------- | ---- | ---------------------- | - | inRotationVector | Array<number> | Yes| Rotation vector to rotate.| - | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes| Direction of the coordinate system.| - | callback | AsyncCallback<Array<number>> | Yes| Callback used to return the rotation vector after being rotated.| + | inRotationVector | Array<number> | Yes | Rotation vector to rotate. | + | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | + | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| - Example @@ -1207,18 +1698,20 @@ Rotates a rotation vector so that it can represent the coordinate system in diff transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> -Rotates a rotation vector so that it can represent the coordinate system in different ways. This method uses a promise to return the result. +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | ---------------- | ----------------------------------------- | ---- | ---------------- | - | inRotationVector | Array<number> | Yes| Rotation vector to rotate.| - | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes| Direction of the coordinate system.| + | inRotationVector | Array<number> | Yes | Rotation vector to rotate. | + | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| - Return value - | Type| Description| + | Type | Description | | ---------------------------------- | ---------------------- | | Promise<Array<number>> | Promise used to return the rotation vector after being converted.| @@ -1243,7 +1736,9 @@ Rotates a rotation vector so that it can represent the coordinate system in diff getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void -Obtains the geomagnetic field of a geographic location. This method uses a callback to return the result. +Obtains the geomagnetic field of a geographic location. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters | Name| Type| Mandatory| Description| @@ -1270,7 +1765,9 @@ Obtains the geomagnetic field of a geographic location. This method uses a callb getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> -Obtains the geomagnetic field of a geographic location. This method uses a promise to return the result. +Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters | Name| Type| Mandatory| Description| @@ -1299,15 +1796,17 @@ Obtains the geomagnetic field of a geographic location. This method uses a promi getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void -Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This method uses a callback to return the result. +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | --------------- | --------------------------- | ---- | ------------------------------------- | - | seaPressure | number | Yes| Sea-level atmospheric pressure, in hPa.| - | currentPressure | number | Yes| Current atmospheric pressure at the altitude where the device is located, in hPa.| - | callback | AsyncCallback<number> | Yes| Callback used to return the altitude, in meters.| + | seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | + | currentPressure | number | Yes | Current atmospheric pressure at the altitude where the device is located, in hPa.| + | callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | - Example @@ -1326,18 +1825,20 @@ Obtains the altitude at which the device is located based on the sea-level atmos getAltitude(seaPressure: number, currentPressure: number): Promise<number> -Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This method uses a promise to return the result. +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | --------------- | ------ | ---- | ------------------------------------- | - | seaPressure | number | Yes| Sea-level atmospheric pressure, in hPa.| - | currentPressure | number | Yes| Atmospheric pressure at the altitude where the device is located, in hPa.| + | seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | + | currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| - Return value - | Type| Description| + | Type | Description | | --------------------- | ------------------------------------ | | Promise<number> | Promise used to return the altitude, in meters.| @@ -1357,14 +1858,16 @@ Obtains the altitude at which the device is located based on the sea-level atmos getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void -Obtains the magnetic dip based on the inclination matrix. This method uses a callback to return the result. +Obtains the magnetic dip based on the inclination matrix. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | ----------------- | --------------------------- | ---- | ---------------------------- | - | inclinationMatrix | Array<number> | Yes| Inclination matrix.| - | callback | AsyncCallback<number> | Yes| Callback used to return the magnetic dip, in radians.| + | inclinationMatrix | Array<number> | Yes | Inclination matrix. | + | callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| - Example @@ -1383,17 +1886,19 @@ Obtains the magnetic dip based on the inclination matrix. This method uses a cal getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> -Obtains the magnetic dip based on the inclination matrix. This method uses a promise to return the result. +Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | ----------------- | ------------------- | ---- | -------------- | - | inclinationMatrix | Array<number> | Yes| Inclination matrix.| + | inclinationMatrix | Array<number> | Yes | Inclination matrix.| - Return value - | Type| Description| + | Type | Description | | --------------------- | ---------------------------- | | Promise<number> | Promise used to return the magnetic dip, in radians.| @@ -1412,15 +1917,17 @@ Obtains the magnetic dip based on the inclination matrix. This method uses a pro getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void -Obtains the angle change between two rotation matrices. This method uses a callback to return the result. +Obtains the angle change between two rotation matrices. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | --------------------- | ---------------------------------------- | ---- | --------------------------------- | - | currentRotationMatrix | Array<number> | Yes| Current rotation matrix.| - | preRotationMatrix | Array<number> | Yes| The other rotation matrix.| - | callback | AsyncCallback<Array<number>> | Yes| Callback used to return the angle change around the z, x, and y axes.| + | currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | + | preRotationMatrix | Array<number> | Yes | The other rotation matrix. | + | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| - Example @@ -1443,18 +1950,20 @@ Obtains the angle change between two rotation matrices. This method uses a callb getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> -Obtains the angle change between two rotation matrices. This method uses a promise to return the result. +Obtains the angle change between two rotation matrices. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | --------------------- | ------------------- | ---- | ------------------ | - | currentRotationMatrix | Array<number> | Yes| Current rotation matrix.| - | preRotationMatrix | Array<number> | Yes| The other rotation matrix.| + | currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| + | preRotationMatrix | Array<number> | Yes | Rotation matrix.| - Return value - | Type| Description| + | Type | Description | | ---------------------------------- | --------------------------------- | | Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| @@ -1477,14 +1986,16 @@ Obtains the angle change between two rotation matrices. This method uses a promi createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void -Converts a rotation vector into a rotation matrix. This method uses a callback to return the result. +Converts a rotation vector into a rotation matrix. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | -------------- | ---------------------------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes| Rotation vector to convert.| - | callback | AsyncCallback<Array<number>> | Yes| Callback used to return the rotation matrix.| + | rotationVector | Array<number> | Yes | Rotation vector to convert.| + | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| - Example @@ -1507,17 +2018,19 @@ Converts a rotation vector into a rotation matrix. This method uses a callback t createRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> -Converts a rotation vector into a rotation matrix. This method uses a promise to return the result. +Converts a rotation vector into a rotation matrix. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | -------------- | ------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes| Rotation vector to convert.| + | rotationVector | Array<number> | Yes | Rotation vector to convert.| - Return value - | Type| Description| + | Type | Description | | ---------------------------------- | -------------- | | Promise<Array<number>> | Promise used to return the rotation matrix.| @@ -1540,14 +2053,16 @@ Converts a rotation vector into a rotation matrix. This method uses a promise to createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void -Converts a rotation vector into a quaternion. This method uses a callback to return the result. +Converts a rotation vector into a quaternion. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | -------------- | ---------------------------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes| Rotation vector to convert.| - | callback | AsyncCallback<Array<number>> | Yes| Callback used to return the quaternion.| + | rotationVector | Array<number> | Yes | Rotation vector to convert.| + | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | - Example @@ -1570,17 +2085,19 @@ Converts a rotation vector into a quaternion. This method uses a callback to ret createQuaternion(rotationVector: Array<number>): Promise<Array<number>> -Converts a rotation vector into a quaternion. This method uses a promise to return the result. +Converts a rotation vector into a quaternion. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | -------------- | ------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes| Rotation vector to convert.| + | rotationVector | Array<number> | Yes | Rotation vector to convert.| - Return value - | Type| Description| + | Type | Description | | ---------------------------------- | ------------ | | Promise<Array<number>> | Promise used to return the quaternion.| @@ -1603,14 +2120,16 @@ Converts a rotation vector into a quaternion. This method uses a promise to retu getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void -Obtains the device direction based on the rotation matrix. This method uses a callback to return the result. +Obtains the device direction based on the rotation matrix. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | -------------- | ---------------------------------------- | ---- | --------------------------------- | - | rotationMatrix | Array<number> | Yes| Rotation matrix.| - | callback | AsyncCallback<Array<number>> | Yes| Callback used to return the rotation angle around the z, x, and y axes.| + | rotationMatrix | Array<number> | Yes | Rotation matrix. | + | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| - Example @@ -1633,17 +2152,19 @@ Obtains the device direction based on the rotation matrix. This method uses a ca getDirection(rotationMatrix: Array<number>): Promise<Array<number>> -Obtains the device direction based on the rotation matrix. This method uses a promise to return the result. +Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | -------------- | ------------------- | ---- | -------------- | - | rotationMatrix | Array<number> | Yes| Rotation matrix.| + | rotationMatrix | Array<number> | Yes | Rotation matrix.| - Return value - | Type| Description| + | Type | Description | | ---------------------------------- | --------------------------------- | | Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| @@ -1666,15 +2187,17 @@ Obtains the device direction based on the rotation matrix. This method uses a pr createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This method uses a callback to return the result. +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | -------------- | - | gravity | Array<number> | Yes| Gravity vector.| - | geomagnetic | Array<number> | Yes| Geomagnetic vector.| - | callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes| Callback used to return the rotation matrix.| + | gravity | Array<number> | Yes | Gravity vector.| + | geomagnetic | Array<number> | Yes | Geomagnetic vector.| + | callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| - Example @@ -1697,18 +2220,20 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This method uses a promise to return the result. +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor - Parameters - | Name| Type| Mandatory| Description| + | Name | Type | Mandatory| Description | | ----------- | ------------------- | ---- | -------------- | - | gravity | Array<number> | Yes| Gravity vector.| - | geomagnetic | Array<number> | Yes| Geomagnetic vector.| + | gravity | Array<number> | Yes | Gravity vector.| + | geomagnetic | Array<number> | Yes | Geomagnetic vector.| - Return value - | Type| Description| + | Type | Description | | ------------------------------------------------------------ | -------------- | | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| @@ -1731,6 +2256,8 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th Enumerates the sensor types. +**System capability**: SystemCapability.Sensors.Sensor + | Name| Default Value| Description| | -------- | -------- | -------- | @@ -1761,6 +2288,8 @@ Enumerates the sensor types. Describes the timestamp of the sensor data. +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | timestamp | number | Yes| Yes| Timestamp when the sensor reports data.| @@ -1770,6 +2299,8 @@ Describes the timestamp of the sensor data. Describes the acceleration sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1782,6 +2313,8 @@ Describes the acceleration sensor data. It extends from [Response](#response). Describes the linear acceleration sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1794,6 +2327,8 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo Describes the uncalibrated acceleration sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1809,6 +2344,8 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( Describes the gravity sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1821,30 +2358,37 @@ Describes the gravity sensor data. It extends from [Response](#response). Describes the orientation sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Rotation angle of the device around the x-axis, in rad.| -| y | number | Yes| Yes| Rotation angle of the device around the y-axis, in rad.| -| z | number | Yes| Yes| Rotation angle of the device around the z-axis, in rad.| +| alpha | number | Yes| Yes| Rotation angle of the device around the z-axis, in rad.| +| beta | number | Yes| Yes| Rotation angle of the device around the x-axis, in rad.| +| gamma | number | Yes| Yes| Rotation angle of the device around the y-axis, in rad.| ## RotationVectorResponse Describes the rotation vector sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | x | number | Yes| Yes| X-component of the rotation vector.| | y | number | Yes| Yes| Y-component of the rotation vector.| | z | number | Yes| Yes| Z-component of the rotation vector.| +| w | number | Yes| Yes| Scalar.| ## GyroscopeResponse Describes the gyroscope sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1857,6 +2401,8 @@ Describes the gyroscope sensor data. It extends from [Response](#response). Describes the uncalibrated gyroscope sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1872,6 +2418,8 @@ Describes the uncalibrated gyroscope sensor data. It extends from [Response](#re Describes the significant motion sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1882,6 +2430,8 @@ Describes the significant motion sensor data. It extends from [Response](#respon Describes the proximity sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1892,6 +2442,8 @@ Describes the proximity sensor data. It extends from [Response](#response). Describes the ambient light sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1902,6 +2454,8 @@ Describes the ambient light sensor data. It extends from [Response](#response). Describes the Hall effect sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1912,6 +2466,8 @@ Describes the Hall effect sensor data. It extends from [Response](#response). Describes the magnetic field sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1924,6 +2480,8 @@ Describes the magnetic field sensor data. It extends from [Response](#response). Describes the uncalibrated magnetic field sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1939,6 +2497,8 @@ Describes the uncalibrated magnetic field sensor data. It extends from [Response Describes the pedometer sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1949,16 +2509,20 @@ Describes the pedometer sensor data. It extends from [Response](#response). Describes the humidity sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | humidity | number | Yes| Yes| Ambient relative humidity, in a percentage (%).| -## PedometerDetectResponse +## PedometerDetectionResponse Describes the pedometer detection sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1969,6 +2533,8 @@ Describes the pedometer detection sensor data. It extends from [Response](#respo Describes the ambient temperature sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1979,6 +2545,8 @@ Describes the ambient temperature sensor data. It extends from [Response](#respo Describes the barometer sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1989,6 +2557,8 @@ Describes the barometer sensor data. It extends from [Response](#response). Describes the heart rate sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -1999,6 +2569,8 @@ Describes the heart rate sensor data. It extends from [Response](#response). Describes the wear detection sensor data. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -2009,6 +2581,8 @@ Describes the wear detection sensor data. It extends from [Response](#response). Describes the sensor data reporting frequency. +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Description| | -------- | -------- | -------- | | interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| @@ -2017,26 +2591,32 @@ Describes the sensor data reporting frequency. Describes the response for setting the rotation matrix. -| Name| Type| Readable| Writable| Description| +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Readable| Writable| Description | | ----------- | ------------------- | ---- | ---- | ---------- | -| rotation | Array<number> | Yes| Yes| Rotation matrix.| -| inclination | Array<number> | Yes| Yes| Inclination matrix.| +| rotation | Array<number> | Yes | Yes | Rotation matrix.| +| inclination | Array<number> | Yes | Yes | Inclination matrix.| ## CoordinatesOptions Describes the coordinate options. -| Name| Type| Readable| Writable| Description| +**System capability**: SystemCapability.Sensors.Sensor + +| Name| Type| Readable| Writable| Description | | ---- | -------- | ---- | ---- | ----------- | -| x | number | Yes| Yes| X coordinate direction.| -| y | number | Yes| Yes| Y coordinate direction.| +| x | number | Yes | Yes | X coordinate direction.| +| y | number | Yes | Yes | Y coordinate direction.| ## GeomagneticResponse Describes a geomagnetic response object. It extends from [Response](#response). +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | x | number | Yes| Yes| North component of the geomagnetic field.| @@ -2047,9 +2627,12 @@ Describes a geomagnetic response object. It extends from [Response](#response). | levelIntensity | number | Yes| Yes| Horizontal intensity of the magnetic field vector field.| | totalIntensity | number | Yes| Yes| Total intensity of the magnetic field vector.| - ## LocationOptions +Describes the geographical location. + +**System capability**: SystemCapability.Sensors.Sensor + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | latitude | number | Yes| Yes| Latitude.| diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md new file mode 100644 index 0000000000000000000000000000000000000000..1cf0e0c7d4fb1fd4e1c90ab0b55c561f437a3d47 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -0,0 +1,1451 @@ +# Socket + +>![](public_sys-resources/icon-note.gif) **NOTE:** +> +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> + +## Modules to Import + +``` +import socket from '@ohos.net.socket'; +``` + +## socket.constructUDPSocketInstance + +constructUDPSocketInstance\(\): UDPSocket + +Creates a **UDPSocket** object. + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :--------------------------------- | :---------------------- | +| [UDPSocket](#udpsocket) | **UDPSocket** object.| + + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +``` + + +## UDPSocket + +Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object. + +### bind + +bind\(address: NetAddress, callback: AsyncCallback\): void + +Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | +| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}) +``` + + +### bind + +bind\(address: NetAddress\): Promise + +Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | +| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| + + +**Return Value** + +| Type | Description | +| :-------------- | :----------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1}); +promise .then(() => { + console.log('bind success'); +}).catch(err => { + console.log('bind fail'); +}); +``` + + +### send + +send\(options: UDPSendOptions, callback: AsyncCallback\): void + +Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.send({ + data:'Hello, server!', + address: { + address:'192.168.xx.xxx', + port:xxxx, + family:1 + } +}, err=> { + if (err) { + console.log('send fail'); + return; + } + console.log('send success'); +}) +``` + + +### send + +send\(options: UDPSendOptions\): Promise + +Sends data over a UDPSocket connection. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| + +**Return Value** + +| Type | Description | +| :-------------- | :--------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +let promise = udp.send({ + data:'Hello, server!', + address: { + address:'192.168.xx.xxx', + port:xxxx, + family:1 + } +}); +promise.then(() => { + console.log('send success'); +}).catch(err => { + console.log('send fail'); +}); +``` + + +### close + +close\(callback: AsyncCallback\): void + +Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.close(err => { + if (err) { + console.log('close fail'); + return; + } + console.log('close success'); +}) +``` + + +### close + +close\(\): Promise + +Closes a UDPSocket connection. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :-------------- | :----------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +let promise = udp.close(); +promise.then(() => { + console.log('close success'); +}).catch(err => { + console.log('close fail'); +}); +``` + + +### getState + +getState\(callback: AsyncCallback\): void + +Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------- | +| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); + udp.getState((err, data) => { + if (err) { + console.log('getState fail'); + return; + } + console.log('getState success:' + JSON.stringify(data)); + }) +}) +``` + + +### getState + +getState\(\): Promise + +Obtains the status of the UDPSocket connection. This API uses a promise to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :----------------------------------------------- | :----------------------------------------- | +| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); + let promise = udp.getState({}); + promise.then(data => { + console.log('getState success:' + JSON.stringify(data)); + }).catch(err => { + console.log('getState fail'); + }); +}) +``` + + +### setExtraOptions + +setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback\): void + +Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); + udp.setExtraOptions({ + receiveBufferSize:1000, + sendBufferSize:1000, + reuseAddress:false, + socketTimeout:6000, + broadcast:true + }, err=> { + if (err) { + console.log('setExtraOptions fail'); + return; + } + console.log('setExtraOptions success'); + }) +}) +``` + + +### setExtraOptions + +setExtraOptions\(options: UDPExtraOptions\): Promise + +Sets other properties of the UDPSocket connection. This API uses a promise to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| + +**Return Value** + +| Type | Description | +| :-------------- | :--------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}); +promise.then(() => { + console.log('bind success'); + let promise1 = udp.setExtraOptions({ + receiveBufferSize:1000, + sendBufferSize:1000, + reuseAddress:false, + socketTimeout:6000, + broadcast:true + }); + promise1.then(() => { + console.log('setExtraOptions success'); + }).catch(err => { + console.log('setExtraOptions fail'); + }); +}).catch(err => { + console.log('bind fail'); +}); +``` + + +### on\('message'\) + +on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void + +Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | +| type | string | Yes | Event type.
**message**: message receiving event| +| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.on('message', value => { + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); +}); +``` + + +### off\('message'\) + +off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void + +Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | +| type | string | Yes | Event type.
**message**: message receiving event| +| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +let callback = value =>{ + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); +} +udp.on('message', callback); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +udp.off('message', callback); +udp.off('message'); +``` + + +### on\('listening' | 'close'\) + +on\(type: 'listening' | 'close', callback: Callback\): void + +Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type.
- **listening**: data packet message event
- **close**: close event| +| callback | Callback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +udp.on('listening', () => { + console.log("on listening success"); +}); +udp.on('close', () => { + console.log("on close success" ); +}); +``` + + +### off\('listening' | 'close'\) + +off\(type: 'listening' | 'close', callback?: Callback\): void + +Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type.
- **listening**: data packet message event
- **close**: close event| +| callback | Callback\ | No | Callback used to return the result. | + +**Example** + +``` +let udp = socket.constructUDPSocketInstance(); +let callback1 = () =>{ + console.log("on listening, success"); +} +udp.on('listening', callback1); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +udp.off('listening', callback1); +udp.off('listening'); +let callback2 = () =>{ + console.log("on close, success"); +} +udp.on('close', callback2); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +udp.off('close', callback2); +udp.off('close'); +``` + + +### on\('error'\) + +on\(type: 'error', callback: ErrorCallback\): void + +Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------ | +| type | string | Yes | Event type.
**error**: error event| +| callback | ErrorCallback | Yes | Callback used to return the result. | + + +**Example** + +``` +let udp = socket.constructUDPSocketInstance() +udp.on('error', err => { + console.log("on error, err:" + JSON.stringify(err)) +}); +``` + + +### off\('error'\) + +off\(type: 'error', callback?: ErrorCallback\): void + +Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------ | +| type | string | Yes | Event type.
**error**: error event| +| callback | ErrorCallback | No | Callback used to return the result. | + +**Example** + +``` +let udp = socket.constructUDPSocketInstance() +let callback = err =>{ + console.log("on error, err:" + JSON.stringify(err)); +} +udp.on('error', callback); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +udp.off('error', callback); +udp.off('error'); +``` + + +## NetAddress + +Defines the destination address. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| address | string | Yes | Bound IP address. | +| port | number | No | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port. | +| family | number | No | Network protocol type.
- **1**: IPv4
- **2**: IPv6
The default value is **1**.| + +## UDPSendOptions + +Defines the parameters for sending data over the UDPSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------- | ---- | -------------- | +| data | string | Yes | Data to send. | +| address | [NetAddress](#netaddress) | Yes | Destination address.| + +## UDPExtraOptions + +Defines other properties of the UDPSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| ----------------- | ------- | ---- | -------------------------------- | +| broadcast | boolean | No | Whether to send broadcast messages. The default value is **false**. | +| receiveBufferSize | number | No | Size of the receive buffer, in bytes. | +| sendBufferSize | number | No | Size of the send buffer, in bytes. | +| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | +| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms.| + +## SocketStateBase + +Defines the status of the UDPSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | ---------- | +| isBound | boolean | Yes | Whether the connection is in the bound state.| +| isClose | boolean | Yes | Whether the connection is in the closed state.| +| isConnected | boolean | Yes | Whether the connection is in the connected state.| + +## SocketRemoteInfo + +Defines information about the UDPSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| address | string | Yes | Bound IP address. | +| family | string | Yes | Network protocol type.
- IPv4
- IPv6
The default value is **IPv4**.| +| port | number | Yes | Port number. The value ranges from **0** to **65535**. | +| size | number | Yes | Length of the server response message, in bytes. | + +## socket.constructTCPSocketInstance + +constructTCPSocketInstance\(\): TCPSocket + +Creates a **TCPSocket** object. + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + + | Type | Description | + | :--------------------------------- | :---------------------- | + | [TCPSocket](#tcpsocket) | **TCPSocket** object.| + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +``` + + +## TCPSocket + +Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object. + +### bind + +bind\(address: NetAddress, callback: AsyncCallback\): void + +Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | +| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}) +``` + + +### bind + +bind\(address: NetAddress\): Promise + +Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | +| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| + +**Return Value** + +| Type | Description | +| :-------------- | :------------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); +promise.then(() => { + console.log('bind success'); +}).catch(err => { + console.log('bind fail'); +}); +``` + + +### connect + +connect\(options: TCPConnectOptions, callback: AsyncCallback\): void + +Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => { + if (err) { + console.log('connect fail'); + return; + } + console.log('connect success'); +}) +``` + + +### connect + +connect\(options: TCPConnectOptions\): Promise + +Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| + +**Return Value** + +| Type | Description | +| :-------------- | :--------------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise.then(() => { + console.log('connect success') +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### send + +send\(options: TCPSendOptions, callback: AsyncCallback\): void + +Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise.then(() => { + console.log('connect success'); + tcp.send({ + data:'Hello, server!' + },err => { + if (err) { + console.log('send fail'); + return; + } + console.log('send success'); + }) +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### send + +send\(options: TCPSendOptions\): Promise + +Sends data over a TCPSocket connection. This API uses a promise to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| + +**Return Value** + +| Type | Description | +| :-------------- | :------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise1.then(() => { + console.log('connect success'); + let promise2 = tcp.send({ + data:'Hello, server!' + }); + promise2.then(() => { + console.log('send success'); + }).catch(err => { + console.log('send fail'); + }); +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### close + +close\(callback: AsyncCallback\): void + +Closes a TCPSocket connection. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +tcp.close(err => { + if (err) { + console.log('close fail'); + return; + } + console.log('close success'); +}) +``` + + +### close + +close\(\): Promise + +Closes a TCPSocket connection. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :-------------- | :----------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.close(); +promise.then(() => { + console.log('close success'); +}).catch(err => { + console.log('close fail'); +}); +``` + + +### getRemoteAddress + +getRemoteAddress\(callback: AsyncCallback\): void + +Obtains the remote address of a TCPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ---------- | +| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.| + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise.then(() => { + console.log('connect success'); + tcp.getRemoteAddress((err, data) => { + if (err) { + console.log('getRemoteAddressfail'); + return; + } + console.log('getRemoteAddresssuccess:' + JSON.stringify(data)); + }) +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### getRemoteAddress + +getRemoteAddress\(\): Promise + +Obtains the remote address of a TCPSocket connection. This API uses a promise to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :------------------------------------------ | :------------------------------------------ | +| Promise<[NetAddress](#netaddress)> | Promise used to return the result.| + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise1.then(() => { + console.log('connect success'); + let promise2 = tcp.getRemoteAddress(); + promise2.then(() => { + console.log('getRemoteAddress success:' + JSON.stringify(data)); + }).catch(err => { + console.log('getRemoteAddressfail'); + }); +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### getState + +getState\(callback: AsyncCallback\): void + +Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------- | +| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| + + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise.then(() => { + console.log('connect success'); + tcp.getState((err, data) => { + if (err) { + console.log('getState fail'); + return; + } + console.log('getState success:' + JSON.stringify(data)); + }); +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### getState + +getState\(\): Promise + +Obtains the status of the TCPSocket connection. This API uses a promise to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :----------------------------------------------- | :----------------------------------------- | +| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| + + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise.then(() => { + console.log('connect success'); + let promise1 = tcp.getState(); + promise1.then(() => { + console.log('getState success:' + JSON.stringify(data)); + }).catch(err => { + console.log('getState fail'); + }); +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### setExtraOptions + +setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void + +Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise.then(() => { + console.log('connect success'); + tcp.setExtraOptions({ + keepAlive: true, + OOBInline: true, + TCPNoDelay: true, + socketLinger: { on:true, linger:10 }, + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: true, + socketTimeout: 3000, + },err => { + if (err) { + console.log('setExtraOptions fail'); + return; + } + console.log('setExtraOptions success'); + }); +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### setExtraOptions + +setExtraOptions\(options: TCPExtraOptions\): Promise + +Sets other properties of the TCPSocket connection. This API uses a promise to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| + +**Return Value** + +| Type | Description | +| :-------------- | :--------------------------------------------------- | +| Promise\ | Promise used to return the result.| + + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +promise.then(() => { + console.log('connect success'); + let promise1 = tcp.setExtraOptions({ + keepAlive: true, + OOBInline: true, + TCPNoDelay: true, + socketLinger: { on:true, linger:10 }, + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: true, + socketTimeout: 3000, + }); + promise1.then(() => { + console.log('setExtraOptions success'); + }).catch(err => { + console.log('setExtraOptions fail'); + }); +}).catch(err => { + console.log('connect fail'); +}); +``` + + +### on\('message'\) + +on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void + +Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | +| type | string | Yes | Event type.
**message**: message receiving event| +| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +tcp.on('message', value => { + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo) +}); +``` + + +### off\('message'\) + +off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void + +Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | +| type | string | Yes | Event type.
**message**: message receiving event| +| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let callback = value =>{ + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); +} +tcp.on('message', callback); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +tcp.off('message', callback); +tcp.off('message'); +``` + + +### on\('connect' | 'close'\) + +on\(type: 'connect' | 'close', callback: Callback\): void + +Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type.
- **connect**: connection event
- **close**: close event| +| callback | Callback\ | Yes | Callback used to return the result. | + + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +tcp.on('connect', () => { + console.log("on connect success") +}); +tcp.on('close', data => { + console.log("on close success") +}); +``` + + +### off\('connect' | 'close'\) + +off\(type: 'connect' | 'close', callback?: Callback\): void + +Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type.
- **connect**: connection event
- **close**: close event| +| callback | Callback\ | No | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let callback1 = () =>{ + console.log("on connect success"); +} +tcp.on('connect', callback1); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +tcp.off('connect', callback1); +tcp.off('connect'); +let callback2 = () =>{ + console.log("on close success"); +} +tcp.on('close', callback2); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +tcp.off('close', callback2); +tcp.off('close'); +``` + + +### on\('error'\) + +on\(type: 'error', callback: ErrorCallback\): void + +Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------ | +| type | string | Yes | Event type.
**error**: error event| +| callback | ErrorCallback | Yes | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +tcp.on('error', err => { + console.log("on error, err:" + JSON.stringify(err)) +}); +``` + + +### off\('error'\) + +off\(type: 'error', callback?: ErrorCallback\): void + +Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------ | +| type | string | Yes | Event type.
**error**: error event| +| callback | ErrorCallback | No | Callback used to return the result. | + +**Example** + +``` +let tcp = socket.constructTCPSocketInstance(); +let callback = err =>{ + console.log("on error, err:" + JSON.stringify(err)); +} +tcp.on('error', callback); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +tcp.off('error', callback); +tcp.off('error'); +``` + + +## TCPConnectOptions + +Defines TCPSocket connection parameters. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------- | ---- | -------------------------- | +| address | [NetAddress](#netaddress) | Yes | Bound IP address and port number. | +| timeout | number | No | Timeout duration of the TCPSocket connection, in ms.| + +## TCPSendOptions + +Defines the parameters for sending data over the TCPSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| data | string | Yes | Data to send. | +| encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| + +## TCPExtraOptions + +Defines other properties of the TCPSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| ----------------- | ------- | ---- | ------------------------------------------------------------ | +| keepAlive | boolean | No | Whether to keep the connection alive. The default value is **false**. | +| OOBInline | boolean | No | Whether to enable OOBInline. The default value is **false**. | +| TCPNoDelay | boolean | No | Whether to enable no-delay on the TCPSocket connection. The default value is **false**. | +| socketLinger | Object | Yes | Socket linger.
- **on**: whether to enable socket linger. The value true means to enable socket linger and false means the opposite.
- **linger**: linger time, in ms. The value ranges from **0** to **65535**.
Specify this parameter only when **on** is set to **true**.| +| receiveBufferSize | number | No | Size of the receive buffer, in bytes. | +| sendBufferSize | number | No | Size of the send buffer, in bytes. | +| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | +| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. | diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 902e9adeedc9de943a117461ccfcae4e6bfa1acb..6f2e389b4d20da87ddc6fde5613c8ab98f5aa72f 100644 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -14,28 +14,26 @@ This module provides common utility functions, such as **TextEncoder** and **Tex import util from '@ohos.util'; ``` -## System Capabilities - -SystemCapability.Utils.Lang - ## util.printf printf(format: string, ...args: Object[]): string Prints the input content in a formatted string. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | format | string | Yes| Format of the string to print.| | ...args | Object[] | No| Data to format.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | String in the specified format.| -- Example +**Example** ``` var res = util.printf("%s", "hello world!"); console.log(res); @@ -48,17 +46,19 @@ getErrorString(errno: number): string Obtains detailed information about a system error code. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | errno | number | Yes| Error code generated.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Detailed information about the error code.| -- Example +**Example** ``` var errnum = 10; // 10 is the system error code. var result = util.getErrorString(errnum); @@ -72,17 +72,20 @@ callbackWrapper(original: Function): (err: Object, value: Object )=>void Calls back an asynchronous function. In the callback, the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved), and the second parameter indicates the resolved value. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | original | Function | Yes| Asynchronous function.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Function | Callback, in which the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved) and the second parameter indicates the resolved value.| -- Example +**Example** ``` async function promiseFn() { return Promise.reject('value'); @@ -101,17 +104,19 @@ promiseWrapper(original: (err: Object, value: Object) => void): Object Processes an asynchronous function and returns a promise version. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | original | Function | Yes| Asynchronous function to process.| + | original | Function | Yes| Asynchronous function.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise version.| -- Example +**Example** ``` function aysnFun(str1, str2, callback) { if (typeof str1 === 'string' && typeof str2 === 'string') { @@ -129,12 +134,13 @@ Processes an asynchronous function and returns a promise version. ## TextDecoder - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| encoding | string | Yes| No| Encoding format.
- 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.
- 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| | 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.| @@ -145,20 +151,22 @@ constructor(encoding?:string, options?:{ fatal?:boolean;ignoreBOM?:boolean }) A constructor used to create a **TextDecoder** object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | encoding | string | No| Encoding format.| | options | Object | No| Encoding-related options, which include **fatal** and **ignoreBOM**.| **Table 1** options - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fatal | boolean | No| Whether to display fatal errors.| | ignoreBOM | boolean | No| Whether to ignore the BOM.| -- Example +**Example** ``` var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM:true}); ``` @@ -166,28 +174,30 @@ A constructor used to create a **TextDecoder** object. ### decode -decode(input: Unit8Array, options?:{stream?:false}):string +decode(input: Unit8Array, options?:{stream?:false}): string Decodes the input content. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | input | Unit8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| **Table 2** options - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | stream | boolean | No| Whether to allow data blocks in subsequent **decode()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | Data decoded.| -- Example +**Example** ``` var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM:true}); var result = new Uint8Array(6); @@ -208,9 +218,10 @@ Decodes the input content. ## TextEncoder - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | encoding | string | Yes| No| Encoding format. The default format is **utf-8**.| @@ -222,7 +233,9 @@ constructor() A constructor used to create a **TextEncoder** object. -- Example +**System capability**: SystemCapability.Utils.Lang + +**Example** ``` var textEncoder = new util.TextEncoder(); ``` @@ -234,17 +247,19 @@ encode(input?:string):Uint8Array Encodes the input content. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | input | string | Yes| String to encode.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Uint8Array | Encoded text.| -- Example +**Example** ``` var textEncoder = new util.TextEncoder(); var result = new Uint8Array(buffer); @@ -258,18 +273,20 @@ encodeInto(input:string, dest:Uint8Array, ):{ read:number; written:number } Stores the UTF-8 encoded text. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | input | string | Yes| String to encode.| | dest | Uint8Array | Yes| **Uint8Array** instance used to store the UTF-8 encoded text.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Uint8Array | Encoded text.| -- Example +**Example** ``` var that = new util.TextEncoder(); var buffer = new ArrayBuffer(4); @@ -286,13 +303,15 @@ constructor(numerator:number,denominator:number) A constructor used to create a **RationalNumber** object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | numerator | number | Yes| Numerator, which is an integer.| | denominator | number | Yes| Denominator, which is an integer.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); ``` @@ -304,17 +323,19 @@ static createRationalFromString​(rationalString:string):RationalNumber​ Creates a **RationalNumber** object based on the given string. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | rationalString | string | Yes| String used to create the **RationalNumber** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | object | **RationalNumber** object created.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var rational = rationalNumer.creatRationalFromString("3/4"); @@ -327,17 +348,19 @@ compareTo​(another:RationalNumber):number​ Compares this **RationalNumber** object with a given object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var rational = rationalNumer.creatRationalFromString("3/4"); @@ -351,12 +374,14 @@ valueOf():number Obtains the value of this **RationalNumber** object as an integer or a floating-point number. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | An integer or a floating-point number.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.valueOf(); @@ -369,17 +394,19 @@ equals​(obj:Object):boolean Checks whether this **RationalNumber** object equals the given object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | object | Object | Yes| Object used to compare with this **RationalNumber** object.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the two objects are equal; returns **false** otherwise.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var rational = rationalNumer.creatRationalFromString("3/4"); @@ -393,18 +420,20 @@ static getCommonDivisor​(number1:number,number2:number):number Obtains the greatest common divisor of two specified integers. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | number1 | number | Yes| The first integer used to get the greatest common divisor.| | number2 | number | Yes| The second integer used to get the greatest common divisor.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | number | Greatest common divisor obtained.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.getCommonDivisor(4,6); @@ -417,12 +446,15 @@ getNumerator​():number Obtains the numerator of this **RationalNumber** object. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** + | Type| Description| | -------- | -------- | | number | Numerator of this **RationalNumber** object.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.getNumerator(); @@ -435,12 +467,14 @@ getDenominator​():number Obtains the denominator of this **RationalNumber** object. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | Denominator of this **RationalNumber** object.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.getDenominator(); @@ -453,12 +487,14 @@ isZero​():boolean Checks whether this **RationalNumber** object is **0**. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the value of this **RationalNumber** object is **0**; returns **false** otherwise.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.isZero(); @@ -471,12 +507,14 @@ isNaN​():boolean Checks whether this **RationalNumber** object is a Not a Number (NaN). -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if this **RationalNumber** object is a NaN (the denominator and numerator are both **0**); returns **false** otherwise.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.isNaN(); @@ -489,12 +527,14 @@ isFinite​():boolean Checks whether this **RationalNumber** object represents a finite value. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if this **RationalNumber** object represents a finite value (the denominator is not **0**); returns **false** otherwise.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.isFinite(); @@ -507,12 +547,14 @@ toString​():string Obtains the string representation of this **RationalNumber** object. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | string | Returns **NaN** if the numerator and denominator of this object are both **0**; returns a string in Numerator/Denominator format otherwise, for example, **3/5**.| -- Example +**Example** ``` var rationalNumber = new util.RationalNumber(1,2); var result = rationalNumber.toString(); @@ -520,14 +562,15 @@ Obtains the string representation of this **RationalNumber** object. ## LruBuffer8+ - ### Attributes +**System capability**: SystemCapability.Utils.Lang + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | length | number | Yes| No| Total number of values in this buffer.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -542,12 +585,14 @@ constructor(capacity?:number) A constructor used to create an **LruBuffer** instance. The default capacity of the buffer is 64. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | capacity | number | No| Capacity of the **LruBuffer** to create.| -- Example +**Example** ``` var lrubuffer= new util.LruBuffer(); ``` @@ -559,12 +604,14 @@ updateCapacity(newCapacity:number):void Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | newCapacity | number | Yes| New capacity of the **LruBuffer**.| -- Example +**Example** ``` var pro = new util.LruBuffer(); var result = pro.updateCapacity(100); @@ -577,12 +624,14 @@ toString():string Obtains the string representation of this **LruBuffer** object. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | string | String representation of this **LruBuffer** object.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -598,12 +647,14 @@ getCapacity():number Obtains the capacity of this buffer. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | Capacity of this buffer.| -- Example +**Example** ``` var pro = new util.LruBuffer(); var result = pro.getCapacity(); @@ -616,7 +667,9 @@ clear():void Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. -- Example +**System capability**: SystemCapability.Utils.Lang + +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -631,12 +684,14 @@ getCreateCount():number Obtains the number of return values for **createDefault()**. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | Number of return values for **createDefault()**.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(1,8); @@ -650,12 +705,14 @@ getMissCount():number Obtains the number of times that the queried values are mismatched. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | Number of times that the queried values are mismatched.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -670,12 +727,14 @@ getRemovalCount():number Obtains the number of removals from this buffer. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | Number of removals from the buffer.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -691,12 +750,14 @@ getMatchCount():number Obtains the number of times that the queried values are matched. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | Number of times that the queried values are matched.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -711,12 +772,14 @@ getPutCount():number Obtains the number of additions to this buffer. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | number | Number of additions to the buffer.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -730,12 +793,14 @@ isEmpty():boolean Checks whether this buffer is empty. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the buffer does not contain any value.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -749,17 +814,19 @@ get(key:K):V | undefined Obtains the value of the specified key. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key based on which the value is queried.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | V \| undefind | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -773,18 +840,20 @@ put(key:K,value:V):V Adds a key-value pair to this buffer. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key of the key-value pair to add.| | value | V | Yes| Value of the key-value pair to add.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | -- Example +**Example** ``` var pro = new util.LruBuffer(); var result = pro.put(2,10); @@ -797,12 +866,14 @@ values():V[] Obtains all values in this buffer, listed from the most to the least recently accessed. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | V [] | All values in the buffer, listed from the most to the least recently accessed.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -818,12 +889,14 @@ keys():K[] Obtains all keys in this buffer, listed from the most to the least recently accessed. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | K [] | All keys in the buffer, listed from the most to the least recently accessed.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -837,17 +910,19 @@ remove(key:K):V | undefined Removes the specified key and its value from this buffer. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key to remove.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | V \| undefind | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -861,7 +936,9 @@ afterRemoval(isEvict:boolean,key:K,value:V,newValue:V):void Performs subsequent operations after a value is removed. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | isEvict | boolean | No| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| @@ -869,7 +946,7 @@ Performs subsequent operations after a value is removed. | value | V | Yes| Value removed.| | newValue | V | No| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| -- Example +**Example** ``` var arr = []; class ChildLruBuffer extends util.LruBuffer @@ -904,17 +981,19 @@ contains(key:K):boolean Checks whether this buffer contains the specified key. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -928,17 +1007,19 @@ createDefault(key:K):V Creates a value if the value of the specified key is not available. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key of which the value is missing.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | V | Value of the key.| -- Example +**Example** ``` var pro = new util.LruBuffer(); var result = pro.createDefault(50); @@ -951,12 +1032,14 @@ entries():IterableIterator<[K,V]> Obtains a new iterator object that contains all key-value pairs in this object. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | [K, V] | Iterable array.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -970,12 +1053,14 @@ Obtains a new iterator object that contains all key-value pairs in this object. Obtains a two-dimensional array in key-value pairs. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | [K, V] | Two-dimensional array in key-value pairs.| -- Example +**Example** ``` var pro = new util.LruBuffer(); pro.put(2,10); @@ -1027,13 +1112,15 @@ constructor(lowerObj:ScopeType,upperObje:ScopeType) A constructor used to create a **Scope** object with the specified upper and lower limits. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| | upperObj | [ScopeType](#scopetype8) | Yes| Upper limit of the **Scope** object.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1047,12 +1134,14 @@ toString():string Obtains a string representation that contains this **Scope**. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | string | String representation containing the **Scope**.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1067,17 +1156,19 @@ intersect(range:Scope):Scope Obtains the intersection of this **Scope** and the given **Scope**. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | range | [Scope](#scope8) | Yes| **Scope** specified.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | [Scope](#scope8) | Intersection of this **Scope** and the given **Scope**.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1095,18 +1186,20 @@ intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope Obtains the intersection of this **Scope** and the given lower and upper limits. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| | upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | [Scope](#scope8) | Intersection of this **Scope** and the given lower and upper limits.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1123,12 +1216,15 @@ getUpper():ScopeType Obtains the upper limit of this **Scope**. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** + | Type| Description| | -------- | -------- | | [ScopeType](#scopetype8) | Upper limit of this **Scope**.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1143,12 +1239,14 @@ getLower():ScopeType Obtains the lower limit of this **Scope**. -- Return value +**System capability**: SystemCapability.Utils.Lang + +**Return value** | Type| Description| | -------- | -------- | | [ScopeType](#scopetype8) | Lower limit of this **Scope**.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1163,18 +1261,20 @@ expand(lowerObj:ScopeType,upperObj:ScopeType):Scope Obtains the union set of this **Scope** and the given lower and upper limits. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| | upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | [Scope](#scope8) | Union set of this **Scope** and the given lower and upper limits.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1191,17 +1291,19 @@ expand(range:Scope):Scope Obtains the union set of this **Scope** and the given **Scope**. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | range | [Scope](#scope8) | Yes| **Scope** specified.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | [Scope](#scope8) | Union set of this **Scope** and the given **Scope**.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1219,17 +1321,19 @@ expand(value:ScopeType):Scope Obtains the union set of this **Scope** and the given value. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ScopeType](#scopetype8) | Yes| Value specified.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | [Scope](#scope8) | Union set of this **Scope** and the given value.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1245,17 +1349,19 @@ contains(value:ScopeType):boolean Checks whether a value is within this **Scope**. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ScopeType](#scopetype8) | Yes| Value specified.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1271,17 +1377,19 @@ contains(range:Scope):boolean Checks whether a range is within this **Scope**. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | range | [Scope](#scope8) | Yes| Range specified.| + | range | [Scope](#scope8) | Yes| **Scope** specified.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1299,17 +1407,19 @@ clamp(value:ScopeType):ScopeType Limits a value to this **Scope**. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ScopeType](#scopetype8) | Yes| Value specified.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| -- Example +**Example** ``` var tempLower = new Temperature(30); var tempUpper = new Temperature(40); @@ -1328,7 +1438,9 @@ constructor() A constructor used to create a **Base64** object. -- Example +**System capability**: SystemCapability.Utils.Lang + +**Example** ``` var base64 = new util.Base64(); ``` @@ -1340,17 +1452,19 @@ encodeSync(src:Uint8Array):Uint8Array Encodes the input content. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Uint8Array | Uint8Array encoded.| -- Example +**Example** ``` var that = new util.Base64(); var array = new Uint8Array([115,49,51]); @@ -1364,17 +1478,19 @@ encodeToStringSync(src:Uint8Array):string Encodes the input content. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | string | String encoded from the Uint8Array.| -- Example +**Example** ``` var that = new util.Base64(); var array = new Uint8Array([115,49,51]); @@ -1388,17 +1504,19 @@ decodeSync(src:Uint8Array | string):Uint8Array Decodes the input content. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array \| string | Yes| Uint8Array or string to decode.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Uint8Array | Uint8Array decoded.| -- Example +**Example** ``` var that = new util.Base64(); var buff = 'czEz'; @@ -1412,17 +1530,19 @@ encode(src:Uint8Array):Promise<Uint8Array> Encodes the input content asynchronously. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode asynchronously.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| -- Example +**Example** ``` var that = new util.Base64(); var array = new Uint8Array([115,49,51]); @@ -1441,17 +1561,19 @@ encodeToString(src:Uint8Array):Promise<string> Encodes the input content asynchronously. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode asynchronously.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<string> | String obtained after asynchronous encoding.| -- Example +**Example** ``` var that = new util.Base64(); var array = new Uint8Array([115,49,51]); @@ -1467,17 +1589,19 @@ decode(src:Uint8Array | string):Promise<Uint8Array> Decodes the input content asynchronously. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| -- Example +**Example** ``` var that = new util.Base64(); var array = new Uint8Array([99,122,69,122]); @@ -1499,7 +1623,9 @@ constructor() A constructor used to create a **Types** object. -- Example +**System capability**: SystemCapability.Utils.Lang + +**Example** ``` var type = new util.Types(); ``` @@ -1511,17 +1637,19 @@ isAnyArrayBuffer(value: Object):boolean Checks whether the input value is of the **ArrayBuffer** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isAnyArrayBuffer(new ArrayBuffer([])); @@ -1536,17 +1664,19 @@ Checks whether the input value is of the **ArrayBufferView** type. **ArrayBufferView** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isArrayBufferView(new Int8Array([])); @@ -1559,17 +1689,19 @@ isArgumentsObject(value: Object):boolean Checks whether the input value is of the **arguments** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); function foo() { @@ -1585,17 +1717,19 @@ isArrayBuffer(value: Object):boolean Checks whether the input value is of the **ArrayBuffer** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isArrayBuffer(new ArrayBuffer([])); @@ -1608,17 +1742,19 @@ isAsyncFunction(value: Object):boolean Checks whether the input value is an asynchronous function. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isAsyncFunction(async function foo() {}); @@ -1631,17 +1767,19 @@ isBooleanObject(value: Object):boolean Checks whether the input value is of the **Boolean** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isBooleanObject(new Boolean(true)); @@ -1654,17 +1792,19 @@ isBoxedPrimitive(value: Object):boolean Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isBoxedPrimitive(new Boolean(false)); @@ -1677,17 +1817,19 @@ isDataView(value: Object):boolean Checks whether the input value is of the **DataView** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); const ab = new ArrayBuffer(20); @@ -1701,17 +1843,19 @@ isDate(value: Object):boolean Checks whether the input value is of the **Date** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isDate(new Date()); @@ -1724,17 +1868,19 @@ isExternal(value: Object):boolean Checks whether the input value is of the **native external** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); const data = util.createExternalType(); @@ -1748,17 +1894,19 @@ isFloat32Array(value: Object):boolean Checks whether the input value is of the **Float32Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isFloat32Array(new Float32Array()); @@ -1771,17 +1919,19 @@ isFloat64Array(value: Object):boolean Checks whether the input value is of the **Float64Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isFloat64Array(new Float64Array()); @@ -1794,17 +1944,19 @@ isGeneratorFunction(value: Object):boolean Checks whether the input value is a generator function. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isGeneratorFunction(function* foo() {}); @@ -1817,17 +1969,19 @@ isGeneratorObject(value: Object):boolean Checks whether the input value is a generator object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); function* foo() {} @@ -1842,17 +1996,19 @@ isInt8Array(value: Object):boolean Checks whether the input value is of the **Int8Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isInt8Array(new Int8Array([])); @@ -1865,17 +2021,19 @@ isInt16Array(value: Object):boolean Checks whether the input value is of the **Int16Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isInt16Array(new Int16Array([])); @@ -1888,17 +2046,19 @@ isInt32Array(value: Object):boolean Checks whether the input value is of the **Int32Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isInt32Array(new Int32Array([])); @@ -1911,17 +2071,19 @@ isMap(value: Object):boolean Checks whether the input value is of the **Map** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isMap(new Map()); @@ -1934,17 +2096,19 @@ isMapIterator(value: Object):boolean Checks whether the input value is of the **MapIterator** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); const map = new Map(); @@ -1958,17 +2122,19 @@ isNativeError(value: Object):boolean Checks whether the input value is of the **Error** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isNativeError(new TypeError()); @@ -1981,17 +2147,19 @@ isNumberObject(value: Object):boolean Checks whether the input value is a number object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isNumberObject(new Number(0)); @@ -2004,17 +2172,19 @@ isPromise(value: Object):boolean Checks whether the input value is a promise. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isPromise(Promise.resolve(1)); @@ -2027,17 +2197,19 @@ isProxy(value: Object):boolean Checks whether the input value is a proxy. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); const target = {}; @@ -2052,17 +2224,19 @@ isRegExp(value: Object):boolean Checks whether the input value is of the **RegExp** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isRegExp(new RegExp('abc')); @@ -2075,17 +2249,19 @@ isSet(value: Object):boolean Checks whether the input value is of the **Set** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isSet(new Set()); @@ -2098,17 +2274,19 @@ isSetIterator(value: Object):boolean Checks whether the input value is of the **SetIterator** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); const set = new Set(); @@ -2122,17 +2300,19 @@ isStringObject(value: Object):boolean Checks whether the input value is a string object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isStringObject(new String('foo')); @@ -2141,21 +2321,23 @@ Checks whether the input value is a string object. ### isSymbolObjec8+ -isSymbolObjec(value: Object):boolean +isSymbolObjec(value: Object): boolean Checks whether the input value is a symbol object. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); const symbols = Symbol('foo'); @@ -2171,17 +2353,19 @@ Checks whether the input value is of the **TypedArray** type. **TypedArray** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint16Array**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isTypedArray(new Float64Array([])); @@ -2194,17 +2378,19 @@ isUint8Array(value: Object):boolean Checks whether the input value is of the **Uint8Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isUint8Array(new Uint8Array([])); @@ -2217,17 +2403,19 @@ isUint8ClampedArray(value: Object):boolean Checks whether the input value is of the **Uint8ClampedArray** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isUint8ClampedArray(new Uint8ClampedArray([])); @@ -2240,17 +2428,19 @@ isUint16Array(value: Object):boolean Checks whether the input value is of the **Uint16Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isUint16Array(new Uint16Array([])); @@ -2263,17 +2453,19 @@ isUint32Array(value: Object):boolean Checks whether the input value is of the **Uint32Array** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isUint32Array(new Uint32Array([])); @@ -2286,17 +2478,19 @@ isWeakMap(value: Object):boolean Checks whether the input value is of the **WeakMap** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isWeakMap(new WeakMap()); @@ -2309,17 +2503,19 @@ isWeakSet(value: Object):boolean Checks whether the input value is of the **WeakSet** type. -- Parameters +**System capability**: SystemCapability.Utils.Lang + +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| -- Example +**Example** ``` var that = new util.Types(); var result = that.isWeakSet(new WeakSet()); diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index c08aa21f742a559c6b8867d01d02c627e2620fda..b142bffef838bdbf1a836dd73e9d92dbe15bb100 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -10,7 +10,7 @@ import Vector from '@ohos.util.Vector' ``` -## System Capabilities +## System Capability SystemCapability.Utils.Lang @@ -284,7 +284,7 @@ callbackfn | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the entry that is currently traversed.| | index | number | No| Position index of the entry that is currently traversed.| -| vector | Vector<T> | No| Instance that invokes the **replaceAllElements** method.| +| vector | Vector<T> | No| Instance that invokes the **replaceAllElements** API.| **Example** @@ -321,7 +321,7 @@ callbackfn | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the entry that is currently traversed.| | index | number | No| Position index of the entry that is currently traversed.| -| vector | Vector<T> | No| Instance that invokes the **forEach** method.| +| vector | Vector<T> | No| Instance that invokes the **forEach** API.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index f309d858016300549a829a3572b7c368779b1f78..55c4189e30fccbf66c71fce380642bb9a105805b 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -10,21 +10,16 @@ import vibrator from '@ohos.vibrator'; ``` -## System Capabilities - -SystemCapability.Sensors.MiscDevice - -## Required Permissions - -ohos.permission.VIBRATE - ## vibrator.vibrate vibrate(duration: number): Promise<void> +Triggers vibration with a specific duration. This API uses a promise to return the execution result. + +**Required permissions**: ohos.permission.VIBRATE (a system permission) -Triggers vibration with a specific duration. This method uses a promise to return the execution result. +**System capability**: SystemCapability.Sensors.MiscDevice - Parameters @@ -52,7 +47,11 @@ Triggers vibration with a specific duration. This method uses a promise to retur vibrate(duration: number, callback?: AsyncCallback<void>): void -Triggers vibration with a specific duration. This method uses a callback to return the execution result. +Triggers vibration with a specific duration. This API uses an asynchronous callback to return the execution result. + +**Required permissions**: ohos.permission.VIBRATE (a system permission) + +**System capability**: SystemCapability.Sensors.MiscDevice - Parameters | Name| Type| Mandatory| Description| @@ -76,7 +75,11 @@ Triggers vibration with a specific duration. This method uses a callback to retu vibrate(effectId: EffectId): Promise<void> -Triggers vibration with a specific effect. This method uses a promise to return the execution result. +Triggers vibration with a specific effect. This API uses a promise to return the execution result. + +**Required permissions**: ohos.permission.VIBRATE (a system permission) + +**System capability**: SystemCapability.Sensors.MiscDevice - Parameters | Name| Type| Mandatory| Description| @@ -102,7 +105,11 @@ Triggers vibration with a specific effect. This method uses a promise to return vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void -Triggers vibration with a specific effect. This method uses a callback to return the execution result. +Triggers vibration with a specific effect. This API uses an asynchronous callback to return the execution result. + +**Required permissions**: ohos.permission.VIBRATE (a system permission) + +**System capability**: SystemCapability.Sensors.MiscDevice - Parameters | Name| Type| Mandatory| Description| @@ -126,7 +133,11 @@ Triggers vibration with a specific effect. This method uses a callback to return stop(stopMode: VibratorStopMode): Promise<void> -Stops the vibration based on the specified **stopMode**. This method uses a promise to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this method fails to be called. +Stops the vibration based on the specified **stopMode**. This API uses a promise to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. + +**Required permissions**: ohos.permission.VIBRATE (a system permission) + +**System capability**: SystemCapability.Sensors.MiscDevice - Parameters | Name| Type| Mandatory| Description| @@ -152,7 +163,11 @@ Stops the vibration based on the specified **stopMode**. This method uses a prom stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void; -Stops the vibration based on the specified **stopMode**. This method uses an asynchronous callback to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this method fails to be called. +Stops the vibration based on the specified **stopMode**. This API uses an asynchronous callback to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. + +**Required permissions**: ohos.permission.VIBRATE (a system permission) + +**System capability**: SystemCapability.Sensors.MiscDevice - Parameters | Name| Type| Mandatory| Description| @@ -176,6 +191,8 @@ Stops the vibration based on the specified **stopMode**. This method uses an asy Describes the vibration effect. +**System capability**: SystemCapability.Sensors.MiscDevice + | Name| Default Value| Description| | -------- | -------- | -------- | | EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer.| @@ -185,6 +202,8 @@ Describes the vibration effect. Describes the vibration mode to stop. +**System capability**: SystemCapability.Sensors.MiscDevice + | Name| Default Value| Description| | -------- | -------- | -------- | | VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md new file mode 100644 index 0000000000000000000000000000000000000000..65d7eeb5c49fbe9a0b456333dd043d17835aeaea --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -0,0 +1,627 @@ +# WebSocket + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +>Newly added APIs are defined but not implemented in OpenHarmony 3.1 Release. They will be available for use in OpenHarmony 3.1 MR. + +You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. + +If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event. + + +## Modules to Import + +``` +import webSocket from '@ohos.net.webSocket'; +``` + +## Complete Example + +``` +import webSocket from '@ohos.net.webSocket'; + +var defaultIpAddress = "ws://"; +let ws = webSocket.createWebSocket(); +ws.on('open', (err, value) => { + console.log("on open, status:" + value.status + ", message:" + value.message); + // When receiving the on('open') event, the client can use the send() API to communicate with the server. + ws.send("Hello, server!", (err, value) => { + if (!err) { + console.log("send success"); + } else { + console.log("send fail, err:" + JSON.stringify(err)); + } + }); +}); +ws.on('message', (err, value) => { + console.log("on message, message:" + value); + // When receiving the bye message (the actual message name may differ) from the server, the client proactively disconnects from the server. + if (value === 'bye') { + ws.close((err, value) => { + if (!err) { + console.log("close success"); + } else { + console.log("close fail, err is " + JSON.stringify(err)); + } + }); + } +}); +ws.on('close', (err, value) => { + console.log("on close, code is " + value.code + ", reason is " + value.reason); +}); +ws.on('error', (err) => { + console.log("on error, error:" + JSON.stringify(err)); +}); +ws.connect(defaultIpAddress, (err, value) => { + if (!err) { + console.log("connect success"); + } else { + console.log("connect fail, err:" + JSON.stringify(err)); + } +}); +``` + +## webSocket.createWebSocket + +createWebSocket\(\): WebSocket + +Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events. + +**System capability**: SystemCapability.Communication.NetStack + +**Return Value** + +| Type | Description | +| :---------------------------------- | :----------------------------------------------------------- | +| [WebSocket](#websocket) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.| + +**Example** + +``` +let ws = webSocket.createWebSocket(); +``` + + +## WebSocket + +Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#webSocketcreatewebsocket) to create a **WebSocket** object. + +### connect + +connect\(url: string, callback: AsyncCallback\): void + +Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------------- | +| url | string | Yes | URL for establishing a WebSocket connection.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +ws.connect(url, (err, value) => { + if (!err) { + console.log("connect success"); + } else { + console.log("connect fail, err:" + JSON.stringify(err)) + } +}); +``` + + +### connect + +connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void + +Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------------------------------------- | +| url | string | Yes | URL for establishing a WebSocket connection. | +| options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +ws.connect(url, { + header: { + "key": "value", + "key2": "value2" + } +}, (err, value) => { + if (!err) { + console.log("connect success"); + } else { + console.log("connect fail, err:" + JSON.stringify(err)) + } +}); +``` + + +### connect + +connect\(url: string, options?: WebSocketRequestOptions\): Promise + +Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------- | ---- | ------------------------------------------------------- | +| url | string | Yes | URL for establishing a WebSocket connection. | +| options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| + +**Return Value** + +| Type | Description | +| :----------------- | :-------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +let promise = ws.connect(url); +promise.then((value) => { + console.log("connect success") +}).catch((err) => { + console.log("connect fail, error:" + JSON.stringify(err)) +}); +``` + + +### send + +send\(data: string | ArrayBuffer, callback: AsyncCallback\): void + +Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------ | +| data | string \| ArrayBuffer 8+ | Yes | Data to send.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +ws.connect(url, (err, value) => { + ws.send("Hello, server!", (err, value) => { + if (!err) { + console.log("send success"); + } else { + console.log("send fail, err:" + JSON.stringify(err)) + } + }); +}); +``` + + +### send + +send\(data: string | ArrayBuffer\): Promise + +Sends data through a WebSocket connection. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| data | string \| ArrayBuffer 8+ | Yes | Data to send.| + +**Return Value** + +| Type | Description | +| :----------------- | :-------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +ws.connect(url, (err, value) => { + let promise = ws.send("Hello, server!"); + promise.then((value) => { + console.log("send success") + }).catch((err) => { + console.log("send fail, error:" + JSON.stringify(err)) + }); +}); +``` + + +### close + +close\(callback: AsyncCallback\): void + +Closes a WebSocket connection. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +ws.close((err, value) => { + if (!err) { + console.log("close success") + } else { + console.log("close fail, err is " + JSON.stringify(err)) + } +}); +``` + + +### close + +close\(options: WebSocketCloseOptions, callback: AsyncCallback\): void + +Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ----------------------------------------------------- | +| options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +ws.close({ + code: 1000, + reason: "your reason" +}, (err, value) => { + if (!err) { + console.log("close success") + } else { + console.log("close fail, err is " + JSON.stringify(err)) + } +}); +``` + + +### close + +close\(options?: WebSocketCloseOptions\): Promise + +Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result. + +**Required permission**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------- | ---- | ----------------------------------------------------- | +| options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| + +**Return Value** + +| Type | Description | +| :----------------- | :-------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let url = "ws://" +let promise = ws.close({ + code: 1000, + reason: "your reason" +}); +promise.then((value) => { + console.log("close success") +}).catch((err) => { + console.log("close fail, err is " + JSON.stringify(err)) +}); +``` + + +### on\('open'\) + +on\(type: 'open', callback: AsyncCallback\): void + +Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ----------------------------- | +| type | string | Yes | Event type.
**open**: event indicating that a WebSocket connection has been opened.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + + +**Example** + +``` +let ws = webSocket.createWebSocket(); +ws.on('open', (err, value) => { + console.log("on open, status:" + value.status + ", message:" + value.message); +}); +``` + + +### off\('open'\) + +off\(type: 'open', callback?: AsyncCallback\): void + +Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ----------------------------- | +| type | string | Yes | Event type.
**open**: event indicating that a WebSocket connection has been opened.| +| callback | AsyncCallback\ | No | Callback used to return the result. | + +**Example** + +``` +let ws = webSocket.createWebSocket(); +let callback1 = (err, value) => { + console.log("on open, status:" + value.status + ", message:" + value.message); +} +ws.on('open', callback1); +// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +ws.off('open', callback1); +``` + + +### on\('message'\) + +on\(type: 'message', callback: AsyncCallback\): void + +Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------------- | +| type | string | Yes | Event type.
**message**: event indicating that a message has been received from the server.| +| callback | AsyncCallback\8+\> | Yes | Callback used to return the result. | + + +**Example** + +``` +let ws = webSocket.createWebSocket(); +ws.on('message', (err, value) => { + console.log("on message, message:" + value); +}); +``` + + +### off\('message'\) + +off\(type: 'message', callback?: AsyncCallback\): void + +Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | -------------------------------------------- | +| type | string | Yes | Event type.
**message**: event indicating that a message has been received from the server.| +| callback | AsyncCallback\8+\> | No | Callback used to return the result. | + +**Example** + +``` +let ws = webSocket.createWebSocket(); +ws.off('message'); +``` + + +### on\('close'\) + +on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void + +Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------ | +| type | string | Yes | Event type.
**close**: event indicating that a WebSocket connection has been closed.| +| callback | AsyncCallback<{ code: number, reason: string }> | Yes | Callback used to return the result. | + +**Example** + +``` +let ws = webSocket.createWebSocket(); +ws.on('close', (err, value) => { + console.log("on close, code is " + value.code + ", reason is " + value.reason); +}); +``` + + +### off\('close'\) + +off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void + +Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------ | +| type | string | Yes | Event type.
**close**: event indicating that a WebSocket connection has been closed.| +| callback | AsyncCallback<{ code: number, reason: string }> | No | Callback used to return the result. | + + +**Example** + +``` +let ws = webSocket.createWebSocket(); +ws.off('close'); +``` + + +### on\('error'\) + +on\(type: 'error', callback: ErrorCallback\): void + +Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------- | +| type | string | Yes | Event type.
**error**: event indicating the WebSocket connection has encountered an error.| +| callback | ErrorCallback | Yes | Callback used to return the result. | + + +**Example** + +``` +let ws = webSocket.createWebSocket(); +ws.on('error', (err) => { + console.log("on error, error:" + JSON.stringify(err)) +}); +``` + + +### off\('error'\) + +off\(type: 'error', callback?: ErrorCallback\): void + +Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. + +>![](public_sys-resources/icon-note.gif) **NOTE:** +>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------- | +| type | string | Yes | Event type.
**error**: event indicating the WebSocket connection has encountered an error.| +| callback | ErrorCallback | No | Callback used to return the result. | + +**Example** + +``` +let ws = webSocket.createWebSocket(); +ws.off('error'); +``` + + +## WebSocketRequestOptions + +Defines the optional parameters carried in the request for establishing a WebSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.| + + +## WebSocketCloseOptions + +Defines the optional parameters carried in the request for closing a WebSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| code | number | No | Error code. Set this parameter based on the actual situation. The default value is **1000**.| +| reason | string | No | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").| + +## Result Codes for Closing a WebSocket Connection + +You can customize the result codes sent to the server. The result codes in the following table are for reference only. + +**System capability**: SystemCapability.Communication.NetStack + +| Value | Description | +| :-------- | :----------------- | +| 1000 | Normally closed | +| 1001 | Connection closed by the server | +| 1002 | Incorrect protocol | +| 1003 | Data unable to be processed| +| 1004~1015 | Reserved | diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422916.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422916.png new file mode 100644 index 0000000000000000000000000000000000000000..2eb96b00f11e597fcc3e3d5ef32701e0a4ef5f5b Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422916.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001250678457.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001250678457.gif new file mode 100644 index 0000000000000000000000000000000000000000..6b44b6a2adc2528e13e95bc10d2a67874226a63b Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001250678457.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/radio.gif b/en/application-dev/reference/arkui-ts/figures/radio.gif new file mode 100644 index 0000000000000000000000000000000000000000..23e0e828f6ea0a1953ef754fc8623523c99114de Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/radio.gif differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md b/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md new file mode 100644 index 0000000000000000000000000000000000000000..a67032d829ce865cf58d096b6dce29764b0b5ff3 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md @@ -0,0 +1,63 @@ +# Gauge + + +> ![icon-note.gif](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. + + +Data gauge chart widget, which is used to display data in a ring chart. + + +## Required Permissions + +None + + +## Child Component + +N/A + + +## APIs + +Gauge(value:{value: number, min?: number, max?: number}) + +- Parameter + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | value | number | Yes | - | Current data value. | + | min | number | No | 0 | Minimum value of the current data segment. | + | max | number | No | 100 | Maximum value of the current data segment. | + + +## Attributes + + | Name | Type | Default Value | Description | +| -------- | -------- | -------- | -------- | +| value | number | 0 | Sets the value of the current data chart. | +| startAngle | Angle | -150 | Set the start angle. Clock 0 indicates 0 degree, and the clockwise direction indicates the positive angle. | +| endAngle | Angle | 150 | Sets the end angle position. The clock 0 point is 0 degree, and the clockwise direction is the positive angle. | +| colors | Color \| Array<ColorStop> | - | Set the color of the chart. You can set the pure color or segmental gradient color. | +| strokeWidth | Length | - | Sets the ring thickness of a ring chart. | + + +## Example + + +``` +@Entry +@Component +struct GaugeExample { + build() { + Column() { + Gauge({ value: 50, min: 0, max: 100 }) + .startAngle(210).endAngle(150) + .colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1], [0xD94838, 1]]) + .strokeWidth(20) + .width(200).height(200) + }.width('100%').margin({ top: 5 }) + } +} +``` + +![en-us_image_0000001174422916](figures/en-us_image_0000001174422916.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md new file mode 100644 index 0000000000000000000000000000000000000000..d3180191d5b4e9bb7747ad85885ebe6d31e42767 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md @@ -0,0 +1,323 @@ +# PluginComponent + + +> ![icon-note.gif](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 APIs of this module are system APIs and cannot be called by third-party applications. + + +**<PluginComponent>** allows the UI provided by an external application to be displayed in the application. + + +## Required Permissions + +None + + +## Child Components + +None + + +## APIs + +PluginComponent(value: { template: PluginComponentTemplate, data: any }) + +Creates a **PluginComponent** to display the UI provided by an external application. + +- Parameters + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | value | {
template: PluginComponentTemplate,
data: KVObject
} | Yes | - | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.
**data**: data passed to the **PluginComponent** provider. | + +- PluginComponentTemplate parameters + | Name | Type | Description | + | -------- | -------- | -------- | + | source | string | Component template name. | + | ability | string | Name of the provider ability. | + + +## Events + + | Name | Description | +| -------- | -------- | +| onComplete(callback: () => void) | Triggered when the component loading is complete. | +| onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information. | + + +## PluginComponentManager + +Provides APIs for the **PluginComponent**. You can use these APIs to request components and data and send component templates and data. + + +## Modules to Import + + +``` +import pluginComponentManager from '@ohos.plugincomponent' +``` + + +## Required Permissions + +None + + +## push + +push(param: PushParameters, callback: AsyncCallback<void>): void + +Used by the component provider to send the component and data to the component consumer. + + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | -------- | -------- | -------- | + | param | PushParameters | Yes | Information about the component consumer. For details, see description of PushParameters. | + | callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result. | + +- Description of PushParameters + | Name | Type | Mandatory | Description | + | -------- | -------- | -------- | -------- | + | want | Want | Yes | Ability information of the component consumer. | + | name | string | Yes | Component name. | + | data | KVObject | No | Component data value. | + | extraData | KVObject | No | Additional data value. | + +- Example + For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers). + + +## request + +request(param: RequestParameters, callback: AsyncCallback<RequestCallbackParameters>): void + +Used by the component consumer to request the component from the component provider. + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | -------- | -------- | -------- | + | param | RequestParameters | Yes | Information about the component request. For details, see  description of RequestParameters. | + | callback | AsyncCallback**"push"**: The component provider pushes data to the component consumer.
**"request"**: The component consumer proactively requests data from the component provider. | + | callback | OnPushEventCallback \| OnRequestEventCallback | Yes | Callback used to return the result. For details, see description of callback. | + +- Description of callback + | Name | Type | Description | + | -------- | -------- | -------- | + | OnRequestEventCallback | (source: Want,
name: string,
data: KVObject ) =>RequestEventResult | Callback for the data request event.
**source**: ability information of the component requester.
**name**: name of the requested component.
**data**: additional data.
Return value: request data and result. | + | OnPushEventCallback | (source: Want,
template: PluginComponentTemplate,
data: KVObject,
extraData: KVObject
) => void | Callback used to receive the data pushed by the component provider.
**source**: ability information of the component provider.
**template**: component template.
**data**: component update data.
**extraData**: additional data. | + +- Description of RequestEventResult + | Name | Type | Description | + | -------- | -------- | -------- | + | template | string | Component name. | + | data | KVObject | Component data. | + | extraData | KVObject | Additional data. | + +- Example + For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers). + + +## Example + + +### Using the PluginComponent + + +``` +import plugin from "../../test/plugin_component.js" +import plugincomponent from '@ohos.plugincomponent' + +@Entry +@Component +struct PluginComponentExample { + @StorageLink("plugincount") plugincount: Object[] = [ + { source: 'plugincomponent1', ability: 'com.example.plugin' }, + { source: 'plugintemplate', ability: 'com.example.myapplication' }, + { source: 'plugintemplate', ability: 'com.example.myapplication' }] + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello World') + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button('Push') + .fontSize(50) + .width(400) + .height(100) + .onClick(() => { + plugin.Push() + console.log("Button('Push')") + }) + .margin({ top: 20 }) + Button('Request1') + .fontSize(50) + .width(400) + .height(100) + .margin({ top: 20 }) + .onClick(() => { + plugin.Request1() + console.log("Button('Request1')") + }) + Button('Request2') + .fontSize(50) + .width(400) + .height(100) + .margin({ top: 20 }) + .onClick(() => { + plugin.Request2() + console.log("Button('Request2')") + }) + ForEach(this.plugincount, item => { + PluginComponent({ + template: { source: 'plugincomponent1', ability: 'com.example.plugin' }, + data: { 'countDownStartValue': 'new countDownStartValue' } + }).size({ width: 500, height: 100 }) + .onComplete(() => { + console.log("onComplete") + }) + .onError(({errcode, msg}) => { + console.log("onComplete" + errcode + ":" + msg) + }) + }) + } + .width('100%') + .height('100%') +} +``` + + +### APIs Called by Component Consumers + + +``` +import pluginComponentManager from '@ohos.plugincomponent' + +function onPushListener(source, template, data, extraData) { + console.log("onPushListener template.source=" + template.source) + var jsonObject = JSON.parse(data.componentTemplate.source) + console.log("request_callback1:source json object" + jsonObject) + var jsonArry = jsonObject.ExternalComponent + for (var i in jsonArry) { + console.log(jsonArry[i]) + } + console.log("onPushListener:source json object" + jsonObject) + console.log("onPushListener:source json string" + JSON.stringify(jsonObject)) + console.log("onPushListener template.ability=" + template.ability) + console.log("onPushListener data=" + JSON.stringify(data)) + console.log("onPushListener extraData=" + JSON.stringify(extraData)) +} + +export default { + //register listener + onListener() { + pluginComponentManager.on("push", onPushListener) + }, + Request() { + //The component consumer proactively sends data. + pluginComponentManager.request({ + want: { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + }, + name: "plugintemplate", + data: { + "key_1": "plugin component test", + "key_2": 34234 + }, + jsonPath: "assets/js", + }, + (err, data) => { + console.log("request_callback1: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("request_callback1: componentTemplate.source=" + data.componentTemplate.source) + var jsonObject = JSON.parse(data.componentTemplate.source) + console.log("request_callback1:source json object" + jsonObject) + var jsonArry = jsonObject.ExternalComponent + for (var i in jsonArry) { + console.log(jsonArry[i]) + } + console.log("request_callback1:source json string" + JSON.stringify(jsonObject)) + console.log("request_callback1: data=" + JSON.stringify(data.data)) + console.log("request_callback1: extraData=" + JSON.stringify(data.extraData)) + } + ) + } +} + +// Example of the component provider using the API +import pluginComponentManager from '@ohos.plugincomponent' + +function onRequestListener(source, name, data) { + console.log("onRequestListener name=" + name) + console.log("onRequestListener data=" + JSON.stringify(data)) + return { template: "plugintemplate", data: data } +} + +export default { + //register listener + onListener() { + pluginComponentManager.on("request", onRequestListener) + }, + Push() { + // The component provider proactively sends data. + pluginComponentManager.push( + { + want: { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + }, + name: "plugintemplate", + data: { + "key_1": "plugin component test", + "key_2": 34234 + }, + extraData: { + "extra_str": "this is push event" + }, + jsonPath: "assets/js", + }, + (err, data) => { + console.log("push_callback1: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("push_callback1: componentTemplate.source=" + data.componentTemplate.source) + console.log("push ok!") + } + ) + }, +} +``` diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md new file mode 100644 index 0000000000000000000000000000000000000000..2b1970cdfde2fd84412f62bab07d4535763a2ccc --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md @@ -0,0 +1,84 @@ +# Radio + +> ![icon-note.gif](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 **\** component allows users to select from a set of mutually exclusive options. + + +## Required Permissions + +None + + +## Child Components + +None + + +## APIs + +Radio(options: {value: string, group: string}) + +- Parameters + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | value | string | Yes| - | Value of the current radio button.| + | group | string | Yes| - | Name of the group to which the radio button belongs. Only one radio button in a given group can be selected at a time.| + + +## Attributes + +| Name| Type| Default Value| Description| +| -------- | -------- | -------- | -------- | +| checked | boolean | false | Whether the radio button is selected.| + + +## Events + +| Name| Description| +| -------- | -------- | +| onChange(callback: (value: boolean) => void) | Triggered when the selected state of the radio button changes.
-The value **true** means that the radio button is selected.
-The value **false** means that the radio button is not selected.| + + +## Example + +``` +@Entry +@Component +struct RadioExample { + build() { + Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Column() { + Text('Radio1') + Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true) + .height(50) + .width(50) + .onChange((value: boolean) => { + console.log('Radio1 status is ' + value) + }) + } + Column() { + Text('Radio2') + Radio({ value: 'Radio2', group: 'radioGroup' }).checked(false) + .height(50) + .width(50) + .onChange((value: boolean) => { + console.log('Radio2 status is ' + value) + }) + } + Column() { + Text('Radio3') + Radio({ value: 'Radio3', group: 'radioGroup' }).checked(false) + .height(50) + .width(50) + .onChange((value: boolean) => { + console.log('Radio3 status is ' + value) + }) + } + }.padding({ top: 30 }) + } +} +``` +![](figures/radio.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md index 1f4891eb9c210fd3e59f9338e52359408dd98c87..25d73234a372a9e13f9a693e2e834e45d6bf9cda 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md @@ -20,8 +20,8 @@ Select(options: Array) | Name| Type| Mandatory| Default Value| Description| | ------ | ----------------------------------------------- | ---- | ------ | -------------- | - | value | [ResourceStr](../../ui/ts-types.md#resourcestr) | Yes| - | Value of an option in the drop-down list box.| - | icon | [ResourceStr](../../ui/ts-types.md#resourcestr) | No| - | Icon of an option in the drop-down list box.| + | value | [ResourceStr](../../ui/ts-types.md#ResourceStr) | Yes| - | Value of an option in the drop-down list box.| + | icon | [ResourceStr](../../ui/ts-types.md#ResourceStr) | No| - | Icon of an option in the drop-down list box.| ## Attributes @@ -30,13 +30,13 @@ Select(options: Array) | selected | number | - | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.| | value | string | - | Text of the drop-down button.| | font | [Font](../../ui/ts-types.md) | - | Text font of the drop-down button.| -| fontColor | [ResourceColor](../../ui/ts-types.md#resourcecolor) | - | Text color of the drop-down button.| -| selectedOptionBgColor | [ResourceColor](../../ui/ts-types.md#resourcecolor) | - | Background color of the selected option in the drop-down list box.| +| fontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of the drop-down button.| +| selectedOptionBgColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Background color of the selected option in the drop-down list box.| | selectedOptionFont | [Font](../../ui/ts-types.md) | - | Text font of the selected option in the drop-down list box.| -| selectedOptionFontColor | [ResourceColor](../../ui/ts-types.md#resourcecolor) | - | Text color of the selected option in the drop-down list box.| -| optionBgColor | [ResourceColor](../../ui/ts-types.md#resourcecolor) | - | Background color of an option in the drop-down list box.| +| selectedOptionFontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of the selected option in the drop-down list box.| +| optionBgColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Background color of an option in the drop-down list box.| | optionFont | [Font](../../ui/ts-types.md) | - | Text font of an option in the drop-down list box.| -| optionFontColor | [ResourceColor](../../ui/ts-types.md#resourcecolor) | - | Text color of an option in the drop-down list box.| +| optionFontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of an option in the drop-down list box.| ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md index 5635d1fbed14354d7249b4499813f5c1e43eda94..15a45d1e6ad3083ad6d6a7a19c5af6a2f0dbeb6a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -30,7 +30,7 @@ Slider(value:{value?: number, min?: number, max?: number, step?: number, style?: | max | number | No | 100 | Maximum value. | | step | number | No | 1 | Step of the slider. When the corresponding step is set, the slider slides intermittently. | | style | SliderStyle | No | SliderStyle.OutSet | Style of the slider. | - | direction8+ | [Axis](ts-appendix-enums.md) | No | Axis.Horizontal | Whether the slider moves horizontally or vertically. | + | direction8+ | [Axis](../reference/arkui-ts/ts-appendix-enums.md#axis-enums) | No | Axis.Horizontal | Whether the slider moves horizontally or vertically. | | reverse8+ | boolean | No | false | Whether the slider values are reversed. | - SliderStyle enums diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepper.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepper.md new file mode 100644 index 0000000000000000000000000000000000000000..3218ab57d1d03c099803bb8531b849774a1d3abf --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepper.md @@ -0,0 +1,127 @@ +# Stepper + + +> ![icon-note.gif](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 **<Stepper>** component provides a step navigator. + + +## Required Permissions + +None + + +## Child Components + +Only the child component **<[StepperItem](ts-basic-components-stepperitem.md)>** is supported. + + +## APIs + +Stepper(value?: { index?: number }) + + +- Parameters + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | index | number | No | 0 | Index of the **<StepperItem>** that is currently displayed. | + + +## Attributes + +None + + +## Events + + | Name | Description | +| -------- | -------- | +| onFinish(callback: () => void) | Triggered when the **nextLabel** of the last **<StepperItem>** in the **<Stepper>** is clicked. | +| onSkip(callback: () => void) | Triggered when the current **<StepperItem>** is **ItemState.Skip** and the **nextLabel** is clicked. | +| onChange(callback: (prevIndex?: number, index?: number) => void) | Triggered when the text button on the left or right is clicked to switch between steps.
- **prevIndex**: index of the step page before the switching.
- **index**: index of the step page after the switching, that is, index of the previous or next page. | + + +## Example + + + +``` +@Entry +@Component +struct StepperExample { + @State currentIndex: number = 0 + @State firstState: ItemState = ItemState.Normal + @State secondState: ItemState = ItemState.Normal + + build() { + Stepper({ + index: this.currentIndex + }) { + StepperItem() { + Text('Page One') + .fontSize(35) + .fontColor(Color.Blue) + .width(200) + .lineHeight(50) + .margin({top:250}) + } + .nextLabel('') + .position({x: '35%', y: 0}) + StepperItem() { + Text('Page Two') + .fontSize(35) + .fontColor(Color.Blue) + .width(200) + .lineHeight(50) + .margin({top:250}) + .onClick(()=>{ + this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip + }) + } + .nextLabel('Next') + .prevLabel('Previous') + .status(this.firstState) + .position({x: '35%', y: 0}) + StepperItem() { + Text('Page Three') + .fontSize(35) + .fontColor(Color.Blue) + .width(200) + .lineHeight(50) + .margin({top:250}) + .onClick(()=>{ + this.secondState = this.secondState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting + }) + } + .position({x: '35%', y: 0}) + .status(this.secondState) + StepperItem() { + Text('Page four') + .fontSize(35) + .fontColor(Color.Blue) + .width(200) + .lineHeight(50) + .margin({top:250}) + } + .position({x: '35%', y: 0}) + .nextLabel('Finish') + } + .onFinish(() => { + console.log('onFinish') + }) + .onSkip(() => { + console.log('onSkip') + }) + .onChange((prevIndex: number, index: number) => { + this.currentIndex = index + }) + .align(Alignment.Center) + } +} +``` + + +![en-us_image_0000001250678457](figures/en-us_image_0000001250678457.gif) + diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md new file mode 100644 index 0000000000000000000000000000000000000000..66d7fe9147ad4ebc02af9260c08325dbf94b918b --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -0,0 +1,46 @@ +# StepperItem + + +> ![icon-note.gif](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 **<StepperItem>** component provides an element for the **<Stepper>** component. + + +## Required Permissions + +None + + +## Child Components + +This component supports only one child component. + + +## APIs + +StepperItem() + + +## Attributes + +| Name | Type | Default Value | Description | +| -------- | -------- | -------- | -------- | +| prevLabel | string | - | When the **<Stepper>** contains more than one page, the default value for all pages except the first page is **Back**. | +| nextLabel | string | - | When the stepper contains more than one page, the default value for the last page is **Start**, and the default value for other pages is **Next**. | +| status | ItemState | ItemState.Normal | Status of the **<StepperItem>**. | + +- ItemState enums + | Name | Description | + | -------- | -------- | + | Normal | The right button is clickable and can navigate users to the next **<StepperItem>** when it is clicked.. | + | Disabled | The right button is grayed out and unavailable. | + | Waiting | The right button is not displayed, and a progress bar is displayed instead. | + | Skip | The current **<StepperItem>** is skipped, and the next **<StepperItem>** is displayed. | + + +## Example + +See [Stepper](ts-basic-components-stepper.md). + diff --git a/en/application-dev/security/Readme-EN.md b/en/application-dev/security/Readme-EN.md index a9c7d9b828a8576e0db91e99af8282419242bf7b..a07d7e86e951ca950fed04908591c7c6a6d84014 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -2,4 +2,6 @@ - User Authentication - [User Authentication Overview](userauth-overview.md) - - [User Authentication Development](userauth-guidelines.md) \ No newline at end of file + - [User Authentication Development](userauth-guidelines.md) +- hapsigner + - [hapsigner Guide](hapsigntool-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/security/hapsigntool-guidelines.md b/en/application-dev/security/hapsigntool-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..07cf60d2092a0b13defa654d1b767ec2e40d6391 --- /dev/null +++ b/en/application-dev/security/hapsigntool-guidelines.md @@ -0,0 +1,418 @@ +# hapsigner Guide + +## Overview + +### Function +To ensure the integrity and secure source of OpenHarmony applications, the applications must be signed during the build process. Only signed applications can be installed, run, and debugged on real devices. [developtools_hapsigner](https://gitee.com/openharmony/developtools_hapsigner) provides the source code of the HAP signing tool - hapsigner. This tool can be used to generate key pairs, certificate signing requests (CSRs), certificates, profile signatures, and HAP signatures. + + +### Key Concepts + +The hapsigner tool is implemented based on the Public Key Infrastructure (PKI). Before using this tool, you should understand the following concepts: + + - Asymmetric key pair + + The asymmetric key algorithm is the basis of data signature and signature verification. The hapsigner tool can generate standard asymmetric key pairs, including ECC P384/256 and RSA 2048/3072/4096. + + - CSR + + The CSR contains the public key, subject, and private key signature of a certificate. Before applying for a certificate, you need to generate a CSR based on the key pair and submit the CSR to the Certificate Authority (CA). + - Certificate + + OpenHarmony uses the RFC5280 standard to build the X509 certificate trust system. The OpenHarmony certificates used for application signatures are classified into the root CA certificate, subordinate CA certificate, and application or profile signing certificate. The application signing certificate indicates the identity of the application developer, which ensures the traceability of the source of the applications. The profile signing certificate is used to verify the signature of the profile, which ensures the integrity of the profile. + + - HAP + + OpenHarmony Ability Package (HAP) is a package used to deploy an ability, which is the basic unit for OpenHarmony application development. An OpenHarmony application consists of one or more abilities. + + - Profile + + The profile in a HAP contains information such as the authorized certificate permission and device ID. + +### Constraints + + - hapsigner is developed in Java and must run in JRE 8.0 or later. + + - The scripts, such as the one-click signature script, are developed in Python, and must run on Python 3.5 or later. + + + +## Build + + 1. Check that Gradle 7.1 has been installed. + + ```shell + gradle -v + ``` + + 2. Download the code, open the file directory **developtools_hapsigner/hapsigntool**, and run the following command to build the code: + + ```shell + gradle build + ``` + Or + ```shell + gradle jar + ``` + + 3. Check that **hap-sign-tool.jar** (binary files) is generated in the **./hap_sign_tool/build/libs** directory. + +## Usage Guidelines + +### When to Use + +The OpenHarmony system has a built-in KeyStore (KS) file named **OpenHarmony.p12**. This file contains the root CA certificate, subordinate CA certificate, and application or profile certificate information. The hapsigner tool signs the OpenHarmony applications based on this KS file. + +The usage of hapsigner varies depending on whether an application signing certificate is available. + +- If no application signing certificate is available: + You need to generate a key pair, generate an application signing certificate, sign the profile, and sign the application. +- If an application signing certification is available: + You need to sign the profile, and use the application signing certificate and the local KS file (containing the corresponding key) to sign the application. + +### How to Use + +#### Description +1.Display help information. + + -help # If no parameter is specified, the command help information is displayed by default. + +2.Display the version information. + + -version # Display the tool version information. + + +3.Generate a key pair. + + generate-keypair: Generate a key pair. + ├── -keyAlias # Key alias. It is mandatory. + ├── -keyPwd # Key password. It is optional. + ├── -keyAlg # Key algorithm, which can be RSA or ECC. It is mandatory. + ├── -keySize # Key length. It is mandatory. The key length is 2048, 3072, or 4096 bits if RSA is used and is NIST-P-256 or NIST-P-384 if ECC is used. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory. + ├── -keystorePwd # KS password. It is optional. + +4.Generate a CSR. + + generate-csr: Generate a CSR. + ├── -keyAlias # Key alias. It is mandatory. + ├── -keyPwd # Key password. It is optional. + ├── -subject # Certificate subject. It is mandatory. + ├── -signAlg # Signature algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory. + ├── -keystorePwd # KS password. It is optional. + ├── -outFile # CSR to generate. It is optional. If you do not specify this parameter, the CSR is output to the console. + +5.Generate a root CA or subordinate CA certificate. + + generate-ca: Generate a root CA or subordinate CA certificate. If the key does not exist, generate a key together with the certificate. + ├── -keyAlias # Key alias. It is mandatory. + ├── -keyPwd # Key password. It is optional. + ├── -keyAlg # Key algorithm, which can be RSA or ECC. It is mandatory. + ├── -keySize # Key length. It is mandatory. The key length is 2048, 3072, or 4096 bits if RSA is used and is NIST-P-256 or NIST-P-384 if ECC is used. + ├── -issuer # Issuer of the certificate. It is optional. It indicates a root CA certificate if not specified. + ├── -issuerKeyAlias # Key alias of the issuer. It is optional. It indicates a root CA certificate if not specified. + ├── -issuerKeyPwd # Key password of the issuer. It is optional. + ├── -subject # Certificate subject. It is mandatory. + ├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days. + ├── -signAlg # Signature algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory. + ├── -basicConstraintsPathLen # Path length. It is optional. The default value is 0. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory. + ├── -keystorePwd # KS password. It is optional. + ├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional. + ├── -issuerKeystorePwd # KS password of the issuer. It is optional. + ├── -outFile # File to generate. It is optional. The file is output to the console if this parameter is not specified. + +6.Generate an application debug or release certificate. + + generate-app-cert: Generate an application debug or release certificate. + ├── -keyAlias # Key alias. It is mandatory. + ├── -keyPwd # Key password. It is optional. + ├── -issuer # Issuer of the certificate. It is mandatory. + ├── -issuerKeyAlias # Key alias of the issuer. It is mandatory. + ├── -issuerKeyPwd # Key password of the issuer. It is optional. + ├── -subject # Certificate subject. It is mandatory. + ├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days. + ├── -signAlg # Signature algoritym, which can be SHA256withECDSA or SHA384withECDSA. + ├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional. + ├── -issuerKeystorePwd # KS password of the issuer. It is optional. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory. + ├── -keystorePwd # KS password. It is optional. + ├── -outForm # Format of the certificate to generate. It is optional. The value can be cert or certChain. The default value is certChain. + ├── -rootCaCertFile # Root CA certificate, which is mandatory when outForm is certChain. + ├── -subCaCertFile # Subordinate CA certificate, which is mandatory when outForm is certChain. + ├── -outFile # Certificate file (certificate or certificate chain) to generate. It is optional. The file is output to the console if this parameter is not specified. + +7.Generate a profile debug or release certificate. + + generate-profile-cert: Generate a profile debug or release certificate. + ├── -keyAlias # Key alias. It is mandatory. + ├── -keyPwd # Key password. It is optional. + ├── -issuer # Issuer of the certificate. It is mandatory. + ├── -issuerKeyAlias # Key alias of the issuer. It is mandatory. + ├── -issuerKeyPwd # Key password of the issuer. It is optional. + ├── -subject # Certificate subject. It is mandatory. + ├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days. + ├── -signAlg # Signature algoritym, which can be SHA256withECDSA or SHA384withECDSA. + ├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional. + ├── -issuerKeystorePwd # KS password of the issuer. It is optional. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory. + ├── -keystorePwd # KS password. It is optional. + ├── -outForm # Format of the certificate to generate. It is optional. The value can be cert or certChain. The default value is certChain. + ├── -rootCaCertFile # Root CA certificate, which is mandatory when outForm is certChain. + ├── -subCaCertFile # Subordinate CA certificate, which is mandatory when outForm is certChain. + ├── -outFile # Certificate file (certificate or certificate chain) to generate. It is optional. The file is output to the console if this parameter is not specified. + +8.Generate a common certificate, which can be used to generate a custom certificate. + + generate-cert: Generate a common certificate, which can be used to generate a custom certificate. + ├── -keyAlias # Key alias. It is mandatory. + ├── -keyPwd # Key password. It is optional. + ├── -issuer # Issuer of the certificate. It is mandatory. + ├── -issuerKeyAlias # Key alias of the issuer. It is mandatory. + ├── -issuerKeyPwd # Key password of the issuer. It is optional. + ├── -subject # Certificate subject. It is mandatory. + ├── -validity # Validity period of the certificate. It is optional. The default value is 1095 days. + ├── -keyUsage # Usages of the key. It is mandatory. The key usages include digitalSignature, nonRepudiation, keyEncipherment, + ├ dataEncipherment, keyAgreement, certificateSignature, crlSignature, + ├ encipherOnly, and decipherOnly. Use a comma (,) to separate multiple values. + ├── -keyUsageCritical # Whether keyUsage is a critical option. It is optional. The default value is true. + ├── -extKeyUsage # Extended key usages. It is optional. The extended key usages include clientAuthentication, serverAuthentication, + ├ codeSignature, emailProtection, smartCardLogin, timestamp, and ocspSignature. + ├── -extKeyUsageCritical # Whether extKeyUsage is a critical option. It is optional. The default value is false. + ├── -signAlg # Signature algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory. + ├── -basicConstraints # Whether basicConstraints is contained. It is optional. The default value is false. + ├── -basicConstraintsCritical # Whether basicConstraints is a critical option. It is optional. The default value is false. + ├── -basicConstraintsCa # Whether it is CA. It is optional. The default value is false. + ├── -basicConstraintsPathLen # Path length. It is optional. The default value is 0. + ├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional. + ├── -issuerKeystorePwd # KS password of the issuer. It is optional. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory. + ├── -keystorePwd # KS password. It is optional. + ├── -outFile # Certificate file to generate. It is optional. The file is output to the console if this parameter is not specified. + +9.Sign a provisioning profile. + + sign-profile: Sign a provisioning profile. + ├── -mode # Signing mode, which can be localSign or remoteSign. It is mandatory. + ├── -keyAlias # Key alias. It is mandatory. + ├── -keyPwd # Key password. It is optional. + ├── -profileCertFile # Profile signing certificate (certificate chain, in application or profile certificate, subordinate CA certificate, and root certificate order). It is mandatory. + ├── -inFile # Raw profile template in JSON format (developtools_hapsigner/autosign/UnsgnedReleasedProfileTemplate.json). It is mandatory. + ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory if the signing mode is localSign. + ├── -keystorePwd # KS password. It is optional. + ├── -outFile # Signed provisioning profile to generate, in p7b format. It is mandatory. + +10.Verify the provisioning profile signature. + + verify-profile: Verify the provisioning profile signature. + ├── -inFile # Signed provisioning profile, in p7b format. It is mandatory. + ├── -outFil # Verification result file (including the verification result and profile content), in json format. It is optional. The file is output to the console if this parameter is not specified. + +11.Sign a HAP. + + sign-app: HAP signature. + ├── -mode # Signing mode, which can be localSign, remoteSign, or remoteResign. It is mandatory. + ├── -keyAlias # Key alias. It is mandatory. + ├──-keyPwd # Key password. It is optional. + ├── -appCertFile # Application signing certificate (certificate chain in application or profile certificate, subordinate CA certificate, and root certificate order). It is mandatory. + ├── -profileFile # Singed provisioning profile, in p7b format. It is mandatory. + ├── -profileSigned # Whether the profile is signed. The value 1 means signed, and value 0 means unsigned. The default value is 1. It is optional. + ├── -inForm # Raw file, in .zip (default) or .bin format. It is optional. + ├── -inFile # Raw application package, in HAP or .bin format. It is mandatory. + ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory if the signing mode is localSign. + ├── -keystorePwd # KS password. It is optional. + ├── -outFile # Signed HAP file to generate. It is mandatory. + +12.Verify the HAP signature. + + verify-app: Verify the HAP signature. + ├── -inFile # Signed application file, in HAP or bin format. It is mandatory. + ├── -outCertchain # Signed certificate chain file. It is mandatory. + ├── -outProfile # Profile of the application. It is mandatory. + + +### Procedure +The process of signing a HAP is as follows: + +1. Generate a key pair for an application signing certificate. +2. Generate an application signing certificate. +3. Sign the profile. +4. Signing the HAP. + + +> **Precautions**
+ 1. The ECC algorithm is recommended for generating key pairs for application signatures for security purposes. The RSA algorithm is not recommended.
+ 2. You are advised to place the HAP, profile, **OpenHarmony.p12**, root CA certificate, subordinate CA certificate, and hapsigner in the same directory for easy operation.
+ 3. The related files are in the following directories:
OpenHarmony KS file: **developtools_hapsigner/autosign/result/OpenHarmony.p12**
Root CA certificate: **developtools_hapsigner/autosign/result/rootCA.cer**
Subordinate CA certificate: **developtools_hapsigner/autosign/result/subCA.cer**
Profile signing certificate: **developtools_hapsigner/autosign/result/OpenHarmonyProfileRelease.pem** + + +**1. Generate a key pair for the application signing certificate.** + +Generate a signature key and save it to the KS. + +Example: +```shell +java -jar hap-sign-tool.jar generate-keypair -keyAlias "oh-app1-key-v1" -keyAlg "ECC" -keySize "NIST-P-256" -keystoreFile "OpenHarmony.p12" -keyPwd "123456" -keystorePwd "123456" +``` + > ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
Record the values of **keyAlias**, **keyStorePwd**, and **keyPwd**. These values will be used when the application signing certificate is generated and the HAP is signed. + +The command parameters are described as follows: + + generate-keypair: Generate a key pair for the application signing certificate. + ├── -keyAlias # Alias of the key used to generate the application signing certificate. It is stored in the OpenHarmony.p12 file. It is mandatory. + ├── -keyAlg # Key algorithm. ECC is recommended. It is mandatory. + ├── -keySize # Key length. It is NIST-P-256/NIST-P-384 if ECC is used. It is mandatory. + ├── -keyStoreFile # KS file. OpenHarmony.p12 is recommended. It is mandatory. + ├── -keyStorePwd # KS password. The default password 123456 for OpenHarmony.p12. It is mandatory. + ├── -keyPwd # Key password. It is optional. If this parameter is not specified, the generated key pair has no password. + + + +**2. Generate an application signing certificate.** + +Use the local subordinate CA certificate to issue an application signing certificate. + +Example: + +```shell +java -jar hap-sign-tool.jar generate-app-cert -keyAlias "oh-app1-key-v1" -signAlg "SHA256withECDSA" -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Team,CN= OpenHarmony Application CA" -issuerKeyAlias "openharmony application ca" -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Team,CN=OpenHarmony Application Release" -keystoreFile "OpenHarmony.p12" -subCaCertFile "subCA.cer" -rootCaCertFile "rootCA.cer" -outForm "certChain" -outFile "app1.pem" -keyPwd "123456" -keystorePwd "123456" -issuerKeyPwd "123456" -validity "365" +``` +The command parameters are described as follows: + + generate-app-cert: Generate an application signing certificate. + ├── -keyAlias # Key alias, which must be the same as that in the previous step. + ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory. + ├── -issuer # Issuer of the certificate. Enter the issuer of the subordinate CA certificate. It is mandatory and cannot be changed. + ├── -issuerKeyAlias # Key alias of the issuer. Enter the key alias of the subordinate CA certificate. It is mandatory and cannot be changed. + ├── -subject # Subject of the certificate. Enter the subject in the same sequence specified in the command. It is mandatory. + ├── -issuerKeyPwd # Key password of the issuer. Enter the key password of the subordinate CA certificate. It is mandatory and cannot be changed. In this example, it is 123456. + ├── -keystoreFile # KS file. Use OpenHarmony.p12. It is mandatory and cannot be changed. + ├── -rootCaCertFile # Root certificate. It is mandatory and cannot be changed. + ├── -subCaCertFile # Subordinate CA certificate. It is mandatory and cannot be changed. + ├── -outForm # Format of the certificate file to generate. certChain is recommended. + ├── -outFile # File to generate. It is optional. The file is output to the console if this parameter is not specified. + ├── -keyPwd # Key password. It is optional. It is the key password set when the key pair is generated. + ├── -keystorePwd # KS password. The default value is 123456. + ├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days. +
+ +**3. Sign the profile.** + +Use the profile signature key to sign the profile. + +Example: + +```shell +java -jar hap-sign-tool.jar sign-profile -keyAlias "openharmony application profile release" -signAlg "SHA256withECDSA" -mode "localSign" -profileCertFile "OpenHarmonyProfileRelease.pem" -inFile "UnsgnedReleasedProfileTemplate.json" -keystoreFile "OpenHarmony.p12" -outFile "app1-profile.p7b" -keyPwd "123456" -keystorePwd "123456" +``` +The command parameters are described as follows: + + sign-profile: Sign a profile. + ├── -keyAlias # Alias of the key for generating the profile certificate. It is mandatory and cannot be changed. + ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory. + ├── -mode # Signing mode, which must be localSign. It is mandatory. + ├── -profileCertFile # Profile signing certificate. Use the certificate provided. It is mandatory and cannot be changed. + ├── -inFile # Raw profile template in JSON format (developtools_hapsigner/autosign/UnsgnedReleasedProfileTemplate.json). It is mandatory. + ├── -keystoreFile # KS file. Use OpenHarmony.p12. It is mandatory and cannot be changed. + ├── -outFile # Signed provisioning profile in p7b format to generate. It is mandatory. + ├── -keyPwd # Key password. The default key password in OpenHarmony.p12 is 123456. + ├── -keystorePwd # KS password. The default key password in OpenHarmony.p12 is 123456. +
+ +**4. Sign the HAP.** + +Use the application signature key to sign the HAP. + +Example: +```shell +java -jar hap-sign-tool.jar sign-app -keyAlias "oh-app1-key-v1" -signAlg "SHA256withECDSA" -mode "localSign" -appCertFile "app1.pem" -profileFile "app1-profile.p7b" -inFile "app1-unsigned.zip" -keystoreFile "OpenHarmony.p12" -outFile "app1-signed.hap" -keyPwd "123456" -keystorePwd "123456" +``` + + > ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
The following parameters used are for the scenario where there is no application signing certificate available. If the application signing certificate is available, the following parameters need to be modified:
+-**keyAlias**: Enter the key alias of the application signing certificate. It is mandatory.
+-**appCertFile**: Enter the application signing certificate. It is mandatory.
+-**keystoreFile**: Enter the KS file of the application signing certificate. It is mandatory.
+-**keyPwd**: Enter the key password in the KS file.
+-**keystorePwd**: Enter the KS password in the KS file.
+ +The command parameters are described as follows: + + sign-app: Sign a HAP. + ├──-keyAlias # Key alias, which must be the same as the alias of the key pair generated. It is mandatory. + ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory. + ├── -mode # Signing mode, which must be localSign. It is mandatory. + ├── -appCertFile # Application signing certificate (certificate chain, in application signing certificate, subordinate CA certificate, and root certificate order). Enter the application signing certificate generated. It is mandatory. + ├── -profileFile # Signed provisioning profile in p7b format. Enter the profile generated. It is mandatory. + ├── -inFile # Raw application package. It is mandatory. + ├── -keystoreFile # KS file, which must be the same as the KS file generated. It is mandatory and cannot be changed. + ├── -outFile # Signed file to generate. It is mandatory. + ├── -keyPwd # Key password, which must be actual key password. + ├── -keystorePwd # KS password, which must be actual KS password. + + + + + +## FAQs + +**1. When the application signing certificate is generated, the console displays the result but no file is output.** + + - **Symptom** + + When the tool is used to to generate an application signing certificate, the certificate content is displayed on the console and no certificate is generated. + + - **Possible Causes** + + The path in the **outFile** parameter is incorrect, or the hyphen (-) in **-outFile** is not an English character. + + - **Solution** + + Check and correct the value of **outFile**, and ensure the hyphen (-) in **-outFile** is an English character. + +**2. Failed to sign the profile.** + +- **Symptom** + + When the tool is used to sign a profile, any of the following information is displayed: + + (1) "SIGN_ERROR, code: 107.Details: Failed to verify signature: Wrong key usage". + + (2) "NOT_SUPPORT_ERROR, code: 105.Details: Profile cert 'result\profile1.pem' must a cert chain". + + (3) "VERIFY_ERROR, code: 108.Details: Failed to verify signature: unable to find valid certification path to requested target" + + +- **Possible Causes** + + The possible causes for the error messages are as follows: + + (1) The certificate chain of the profile signing certificate is in incorrect order. + + (2). The profile signing certificate is not a certificate chain. + + (3). The certificate subject is in incorrect sequence, or the **-issuerKeyAlias** parameter set to generate the application signing certificate is incorrect. + +- **Solution** + + (1). Check that the certificate chain is in ascending or descending order of seniority. + + (2). Check that the certificate is a certificate chain. + + (3). Check that the certificate subject is in the C, O, OU, and CN order. + +**3. An error message is displayed when the tool is used to sign a HAP.** + + - **Symptom** + + The following error message is displayed: "NOT_SUPPORT_ERROR, code: 105.Details: SignAlg params is incorrect, signature algorithms include SHA256withECDSA,SHA384withECDSA + + - **Possible Causes** + + The signature algorithm is not supported. Check the value of **signAlg**. + + - **Solution** + + Use ECC to generate the key pair for an application or profile certificate. Use **SHA256withECDSA** or **SHA384withECDSA** as the HAP signature algorithm. diff --git a/en/application-dev/ui/ts-application-resource-access.md b/en/application-dev/ui/ts-application-resource-access.md new file mode 100644 index 0000000000000000000000000000000000000000..1dbba18d4a78462127eb07f69c3306dd02d4d946 --- /dev/null +++ b/en/application-dev/ui/ts-application-resource-access.md @@ -0,0 +1,161 @@ +# Accessing Application Resources + + +## Resource Definition + +Application resources are defined by in the project's **resources** directory, which is organized as follows: + +- Level-1: **base** sub-directory, qualifiers sub-directories, and **rawfile** sub-directory + - The **base** sub-directory is a default directory. If no qualifiers sub-directories in the **resources** directory of the application match the device status, the resource file in the **base** sub-directory will be automatically referenced. + - You need to create qualifiers sub-directories on your own. The name of a qualifiers sub-directory consists of one or more qualifiers that represent the application scenarios or device characteristics, covering the mobile country code (MCC), mobile network code (MNC), language, script, country or region, screen orientation, device type, color mode, and screen density. The qualifiers are separated using underscores (_) or hyphens (-). + - When the resources in the **rawfile** sub-directory are referenced, resource files will not be matched based on the device status. You can directly store resource files in the **rawfile** sub-directory. + +- Level-2: resource sub-directories + - Resource sub-directories store basic elements such as character strings, colors, and floating point numbers, and resource files such as media files. + - Supported files and resource types are listed in the table below: + | File Name | Resource Type | + | -------- | -------- | + | color.json | Color resource. | + | float.json | Resources such as spacing, rounded corners, and fonts. | + | string.json | String resource. | + | plural.json | String resource. | + | media directory | Image resource. | + + +## Referencing Resources + +To reference an application resource in a project, use the **"$r('app.type.name')"** format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource. + +When referencing resources in the **rawfile** sub-directory, use the **"$rawfile('filename')"** format. Currently, **$rawfile** allows only the **<Image>** component to reference image resources. In the format, **filename** indicates the relative path of a file in the **rawfile** directory, and the file name must contain the file name extension. Note that the relative path cannot start with a slash (/). + + +## Example + +Some custom resources in the **base** sub-directory are as follows: + + +``` + resources + ├─ base + │ ├─ element + │ │ ├─ color.json + │ │ ├─ string.json + │ │ └─ float.json + │ └─ media + │ └─ my_background_image.png + └─ rawfile + ├─ test.png + └─ newDir + └─ newTest.png +``` + +The content of the **color.json** file is as follows: + + +``` +{ + "color": [ + { + "name": "color_hello", + "value": "#ffff0000" + }, + { + "name": "color_world", + "value": "#ff0000ff" + } + ] +} +``` + +The content of the **float.json** file is as follows: + + +``` +{ + "float":[ + { + "name":"font_hello", + "value":"28.0fp" + }, + { + "name":"font_world", + "value":"20.0fp" + } + ] +} +``` + +The content of the **string.json** file is as follows: + + +``` +{ + "string":[ + { + "name":"string_hello", + "value":"Hello" + }, + { + "name":"string_world", + "value":"World" + }, + { + "name":"message_arrive", + "value":"We will arrive at %s." + } + ] +} +``` + +The content of the **plural.json** file is as follows: + + +``` +{ + "plural":[ + { + "name":"eat_apple", + "value":[ + { + "quantity":"one", + "value":"%d apple" + }, + { + "quantity":"other", + "value":"%d apples" + } + ] + } + ] +} +``` + + In the **ets** file, you can use the resources defined in the **resources** directory. + +``` +Text($r('app.string.string_hello')) + .fontColor($r('app.color.color_hello')) + .fontSize($r('app.float.font_hello')) +} + +Text($r('app.string.string_world')) + .fontColor($r('app.color.color_world')) + .fontSize($r('app.float.font_world')) +} + +Text($r('app.string.message_arrive', "five of the clock")) // Reference string resources. The second parameter of $r is used to replace %s. + .fontColor($r('app.color.color_hello')) + .fontSize($r('app.float.font_hello')) +} + +Text($r('app.plural.eat_apple', 5, 5)) // Reference plural resources. The first parameter specifies the plural resource, and the second parameter specifies the number of plural resources. The third number indicates the substitute of %d. + .fontColor($r('app.color.color_world')) + .fontSize($r('app.float.font_world')) +} + +Image($r(?app.media.my_background_image creation)) // Reference media resources. + +Image($rawfile( Femaletest.png loaded)) // Reference an image in the rawfile directory. + +Image($rawfile(newDir/newTest.png loaded)) // Reference an image in the rawfile directory. +``` diff --git a/en/application-dev/ui/ts-system-resource-access.md b/en/application-dev/ui/ts-system-resource-access.md new file mode 100644 index 0000000000000000000000000000000000000000..fbdeaceeb58762693645cb6e3b4e214516bce045 --- /dev/null +++ b/en/application-dev/ui/ts-system-resource-access.md @@ -0,0 +1,20 @@ +# Accessing System Resources + + +System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style. + + +To reference a system resource, use the **"$r('sys.type.resource_id')"** format. Wherein: **sys** indicates a system resource; **type** indicates the resource type, which can be **color**, **float**, **string**, or **media**; **resource_id** indicates the resource ID, which is determined when the system resource is provided. For details about available system resource IDs. + +``` +Text('Hello') + .fontColor($r('sys.color.id_color_emphasize')) + .fontSize($r('sys.float.id_text_size_headline1')) + .fontFamily($r('sys.string.id_text_font_family_medium')) + .backgroundColor($r('sys.color.id_color_palette_aux1')) +Image($r('sys.media.ic_app')) + .border({color: $r('sys.color.id_color_palette_aux1'), radius: $r('sys.float.id_corner_radius_button'), width: 2}) + .margin({top: $r('sys.float.id_elements_margin_horizontal_m'), bottom: $r('sys.float.id_elements_margin_horizontal_l')}) + .height(200) + .width(300) +``` diff --git a/en/device-dev/subsystems/subsys-data-relational-database-guide.md b/en/device-dev/subsystems/subsys-data-relational-database-guide.md index d668fc922079dfa5b38633d6c7a9c65a88351942..eeaa439df91494d306ebacd79fd40398d75ffea3 100644 --- a/en/device-dev/subsystems/subsys-data-relational-database-guide.md +++ b/en/device-dev/subsystems/subsys-data-relational-database-guide.md @@ -9,11 +9,11 @@ On the basis of the SQLite database, the RDB allows you to operate data with or The following table describes APIs available for creating and deleting an RDB store. -Table 1 APIs for creating and deleting an RDB store +**Table 1** APIs for creating and deleting an RDB store | Class| API| Description| | ---- | ---- | ---- | -| RdbStoreConfig | RdbStoreConfig(const std::string &path,
StorageMode storageMode = StorageMode::MODE_DISK,
bool readOnly = false,
const std::vector &encryptKey = std::vector(),
const std::string &journalMode = "",
const std::string &syncMode = "",
const std::string &databaseFileType = "",
const std::string &databaseFileSecurityLevel = "") | Configures an RDB store, including setting the name, storage mode, log mode, synchronization mode, and read-only mode, and encrypting the database.
  • **path**: path of the database.
  • **readOnly**: whether the database is read-only.
  • **storageMode**: storage mode.
  • **encryptKey**: key used for database encryption.
  • **journalMode**: database logging mode.
  • **syncMode**: data synchronization mode.
  • **databaseFileType**: database type.
  • **databaseFileSecurityLevel**: security level.
| +| RdbStoreConfig | RdbStoreConfig(const std::string &path,
StorageMode storageMode = StorageMode::MODE_DISK,
bool readOnly = false,
const std::vector &encryptKey = std::vector(),
const std::string &journalMode = "",
const std::string &syncMode = "",
const std::string &databaseFileType = "",
const std::string &databaseFileSecurityLevel = "") | Configures an RDB store, including setting the name, storage mode, log mode, synchronization mode, and read-only mode, and encrypting the RDB store.
- **path**: path of the database.
- **readOnly**: whether the database is read-only.
-  **storageMode**: storage mode.
- **encryptKey**: key used for database encryption.
- **journalMode**: database logging mode.
- **syncMode**: data synchronization mode.
- **databaseFileType**: database type.
- **databaseFileSecurityLevel**: security level. | | RdbOpenCallback | int OnCreate(RdbStore &rdbStore) | Called when an RDB store is created. You can add the method for initializing the table structure and add initialization data used by your application in the callback.| | RdbOpenCallback | int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is upgraded.| | RdbOpenCallback | int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is downgraded.| @@ -22,12 +22,12 @@ Table 1 APIs for creating and deleting an RDB store ### Encrypting an RDB Store -The RDB provides the database encryption capability. When creating an RDB store , you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key. +The RDB provides the database encryption capability. When creating an RDB store, you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key. -Table 2 API for changing the key +**Table 2** API for changing the key | Class| API| Description| | ---- | ---- | ---- | -| RdbStore | int ChangeEncryptKey(const std::vector &newKey) | Changes the encryption key for an RDB store.
Note: The encryption key can be changed only for an encrypted database.| +| RdbStore | int ChangeEncryptKey(const std::vector &newKey) | Changes the encryption key for an RDB store.
Note: The encryption key can be changed only for an encrypted RDB store.| ### Using Predicates @@ -36,7 +36,7 @@ The RDB provides **AbsRdbPredicates** for you to set database operation conditio - **RdbPredicates**: With this class, you do not need to write complex SQL statements. Instead, you can combine SQL statements simply by calling methods in this class, such as **equalTo**, **notEqualTo**, **groupBy**, **orderByAsc**, and **beginsWith**. - **RawRdbPredicates**: With this class, you can set **whereClause** and **whereArgs**, but cannot call methods such as **equalTo**. - Table 7 APIs for RDB predicates + **Table 3** APIs for RDB store predicates | Class| API| Description| | ---- | ---- | ---- | | RdbPredicates | AbsPredicates *EqualTo(std::string field, std::string value) | Sets the **AbsPredicates** to match the field that is equal to the specified value.| @@ -46,6 +46,9 @@ The RDB provides **AbsRdbPredicates** for you to set database operation conditio | RdbPredicates | AbsPredicates *OrderByAsc(std::string field) | Sets the **AbsPredicates** to match the column with values sorted in ascending order.| | RdbPredicates | void SetWhereClause(std::string whereClause) | Sets **whereClause**.| | RdbPredicates | void SetWhereArgs(std::vector\ whereArgs) | Sets **whereArgs**, which indicates the value of the placeholder in **whereClause**.| + | RdbPredicates | AbsRdbPredicates *InDevices(std::vector& devices) | Sets the **AbsPredicates** to specify the remote devices on the network with databases to be synchronized.| + | RdbPredicates | AbsRdbPredicates *InAllDevices() | Sets the **AbsPredicates** to connect to all remote devices on the network when synchronizing distributed databases.| + ### Managing Data in an RDB Store @@ -55,29 +58,29 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th The RDB provides an API for inserting data through **ValuesBucket** in a data table. If the data is added, the row number of the data inserted is returned; otherwise, **-1** is returned. - Table 3 API for inserting data to a data table + **Table 4** APIs for inserting data tables | Class| API| Description| | ---- | ---- | ---- | - | RdbStore | int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) | Inserts data based on the passed table name and data in **ValuesBucket**.
  • **table**: specifies the name of the target table.
  • **initialValues**: specifies the data, stored in **ValuesBucket**, to insert. A series of **put()** methods, such as **PutString(const std::string &columnName, const std::string &value)** and **PutDouble(const std::string &columnName, double value)**, are provided to add data to **ValuesBucket**.
| + | RdbStore | int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) | Inserts data based on the passed table name and data in **ValuesBucket**.
- **table**: specifies the name of the target table.
- **initialValues**: specifies the data, stored in **ValuesBucket**, to insert. A series of **put()** methods, such as **PutString(const std::string &columnName, const std::string &value)** and **PutDouble(const std::string &columnName, double value)**, are provided to add data to **ValuesBucket**. | - Deleting data Call the **delete()** method to delete data meeting the conditions specified by **AbsRdbPredicates**. If the data is deleted, the row number of the deleted data is returned; otherwise, **0** is returned. - Table 5 API for deleting data + **Table 5** API for deleting data | Class| API| Description| | ---- | ---- | ---- | - | RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data.
  • **deletedRows**: specifies the number of rows to delete.
  • **predicates**: specifies the table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies delete conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.
| + | RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data.
- **deletedRows**: specifies the number of rows to delete.
- **predicates**: specifies the table name and conditions for deleting the data.
**AbsRdbPredicates** has the following classes:
- **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.
- **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only. | - Updating data Call the **update()** method to modify data based on the passed data and the conditions specified by **AbsRdbPredicates**. If the data is updated, the row number of the updated data is returned; otherwise, **0** is returned. - Table 4 API for updating data + **Table 6** API for updating data | Class| API| Description| | ---- | ---- | ---- | - | RdbStore | int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) | Updates the data that meets the conditions specified by predicates.
  • **changedRows**: specifies the number of rows to update.
  • **values**: specifies the new data stored in **ValuesBucket**.
  • **predicates**: specifies the table name and conditions for the update operation. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.
| + | RdbStore | int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) | Updates the data that meets the conditions specified by predicates.
- **changedRows**: specifies the number of rows to update.
- **values**: specifies the new data stored in **ValuesBucket**.
- **predicates**: specifies the table name and conditions for the update operation. **AbsRdbPredicates** has the following classes:
- **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.
- **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only. | - Querying data @@ -86,32 +89,75 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th - Call the **query()** method to query data based on the predicates, without passing any SQL statement. - Run the native SQL statement. - Table 6 APIs for querying data + **Table 7** APIs for querying data | Class| API| Description| | ---- | ---- | ---- | - | RdbStore | std::unique_ptr Query(const AbsRdbPredicates &predicates, const std::vector\ columns) | Queries data.
  • **predicates**: specifies the query conditions. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies the query conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only.
  • **columns**: specifies the number of columns returned.
| - | RdbStore | std::unique_ptr QuerySql(const std::string &sql, const std::vector\ &selectionArgs = std::vector\()) | Executes the native SQL statements to query data.
  • **sql**: specifies the native SQL statement.
  • **selectionArgs**: specifies the parameter values corresponding to the placeholders in the SQL statements. Set it to **null** if the **select** statement has no placeholder.
| + | RdbStore | std::unique_ptr Query(const AbsRdbPredicates &predicates, const std::vector\ columns) | Queries data.
- **predicates**: specifies the query conditions. **AbsRdbPredicates** has the following classes:
- **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.
- **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only.
- **columns**: specifies the number of columns returned. | + | RdbStore | std::unique_ptr QuerySql(const std::string &sql, const std::vector\ &selectionArgs = std::vector\()) | Executes the native SQL statements to query data.
- **sql**: specifies the native SQL statement.
- **selectionArgs**: specifies the parameter values corresponding to the placeholders in the SQL statements. Set it to **null** if the **select** statement has no placeholder. | ### Using the Result Set A result set can be regarded as rows of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. - Table 8 APIs for using the result set - | Class| API| Description| - | ---- | ---- | ---- | - | ResultSet | int GoTo(int offset) | Moves the result set forwards or backwards by the specified offset relative to its current position.| - | ResultSet | int GoToRow(int position) | Moves the result set to the specified row.| - | ResultSet | int GoToNextRow() | Moves the result set to the next row.| - | ResultSet | int GoToPreviousRow() | Moves the result set to the previous row.| - | ResultSet | int IsStarted(bool &result) | Checks whether the result set has been moved.| - | ResultSet | int IsEnded(bool &result) | Checks whether the result set is moved after the last line.| - | ResultSet | int IsAtFirstRow(bool &result) | Checks whether the result set is located in the first row.| - | ResultSet | int IsAtLastRow(bool &result) | Checks whether the result set is located in the last row.| - | ResultSet | int GetRowCount(int &count) | Obtains the number of rows in the result set.| - | ResultSet | int GetColumnCount(int &count) | Obtains the number of columns in the result set.| - | ResultSet | int GetString(int columnIndex, std::string &value) | Obtains the values in the specified column of the current row, in strings.| - | ResultSet | int GetBlob(int columnIndex, std::vector\ &blob) | Obtains the values in the specified column of the current row, in a byte array.| - | ResultSet | int GetDouble(int columnIndex, double &value) | Obtains the values in the specified column of the current row, in double.| +**Table 8** APIs for using the result set +| Class| API| Description| +| ---- | ---- | ---- | +| ResultSet | int GoTo(int offset) | Moves the result set forwards or backwards by the specified offset relative to its current position.| +| ResultSet | int GoToRow(int position) | Moves the result set to the specified row.| +| ResultSet | int GoToNextRow() | Moves the result set to the next row.| +| ResultSet | int GoToPreviousRow() | Moves the result set to the previous row.| +| ResultSet | int IsStarted(bool &result) | Checks whether the result set has been moved.| +| ResultSet | int IsEnded(bool &result) | Checks whether the result set is moved after the last line.| +| ResultSet | int IsAtFirstRow(bool &result) | Checks whether the result set is located in the first row.| +| ResultSet | int IsAtLastRow(bool &result) | Checks whether the result set is located in the last row.| +| ResultSet | int GetRowCount(int &count) | Obtains the number of rows in the result set.| +| ResultSet | int GetColumnCount(int &count) | Obtains the number of columns in the result set.| +| ResultSet | int GetString(int columnIndex, std::string &value) | Obtains the values in the specified column of the current row, in strings.| +| ResultSet | int GetBlob(int columnIndex, std::vector\ &blob) | Obtains the values in the specified column of the current row, in a byte array.| +| ResultSet | int GetDouble(int columnIndex, double &value) | Obtains the values in the specified column of the current row, in double.| + +### Setting a List of Distributed Tables + +You can set a list of distributed tables for data operations across devices. + +**Table 9** API for setting a distributed table list +| Class| API| Description| +| ---- | ---- | ---- | +| RdbStore | bool SetDistributedTables(const std::vector& tables) | Sets a list of distributed tables.
- **tables**: specifies the names of the distributed tables to set. | + +### Obtaining the Distributed Table Name for a Remote Device + +When querying the RDB store of a remote device, you need to use the distributed table name. You can obtain the distributed table name of a remote device based on the local table name. + +**Table 10** API for obtaining the distributed table name of a remote device + +| Class| API| Description| +| ---- | ---- | ---- | +| RdbStore | std::string ObtainDistributedTableName(const std::string& device, const std::string& table) | Obtains the distributed table name of a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device.
- **device**: specifies the ID of the remote device.
- **table**: specifies the name of the local table. | + +### Synchronizing Data Between Devices + +**Table 11** API for cross-device data synchronization + +| Class| API| Description| +| ---- | ---- | ---- | +| RdbStore | bool Sync(const SyncOption& option, const AbsRdbPredicates& predicate, const SyncCallback& callback) | Synchronizes data between devices.
- **option**: specifies synchronization options, which include the following:
**mode**: specifies how data is synchronized. The value **push** means to push data from the local device to the remote device; the value **pull** means to pull data from the remote device to the local device.
**isBlock**: specifies whether the invocation of this function is blocked.
- **callback**: specifies the callback used to return the result. | + +### Registering an RDB Store Observer + +**Table 12** API for registering an observer + +| Class| API| Description| +| ---- | ---- | ---- | +| RdbStore | bool Subscribe(const SubscribeOption& option, RdbStoreObserver *observer) | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **option**: specifies the subscription type.
- **observer**: specifies the observer of data changes in the RDB store. | + +### Unregistering an RDB Store Observer + +**Table 13** API for unregistering an observer + +| Class| API| Description| +| ---- | ---- | ---- | +| RdbStore | bool UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer) | Unregisters the observer of the specified type to unsubscribe from distributed data changes.
- **option**: specifies the subscription type to unregister.
- **observer**: specifies the observer to unregister. | ## Constraints @@ -121,7 +167,7 @@ None. 1. Create an RDB store. - a. Configure the RDB store attributes, including the database name, storage mode, and read-only mode. + a. Configure the RDB store attributes, including the RDB store name, storage mode, and read-only mode. b. Initialize the table structure and related data in the RDB store. @@ -155,6 +201,8 @@ None. b. Call the **insert()** method to insert data into the RDB store. + c. Create an RDB store. + The sample code is as follows: ``` ValuesBucket values; @@ -186,3 +234,76 @@ None. std::unique_ptr resultSet = store->Query(predicates, columns) resultSet.goToNextRow(); ``` + +4. Set the distributed tables to be synchronized. + + Call the **SetDistributedTables()** method to set the distributed tables to be synchronized. + + The sample code is as follows: + + ``` + store->SetDistributedTables("test"); + ``` + +5. Synchronize data. + + a. Set the data synchronization mode and block status. + + b. Constructs an **AbsPredicates** object to specify remote devices within the network to be synchronized. + + c. Call the **Sync()** method to synchronize data. + + The sample code is as follows: + + ``` + SyncOption option; + option.mode = PUSH; + option.isBlock = true; + AbsRdbPredicates predicate("test"); + predicate.InAllDevices(); + store->Sync(option, predicate, [] (const SyncResult& result) { + for (const auto& [device, status] : result) { + LogI("device=%s status=%d", device.c_str(), status); + } + }); + ``` + +6. Subscribe to distributed data. + + a. Override the **OnChange()** function. + + b. Define the distributed data subscription type. + + c. Call APIs to subscribe to or unsubscribe from distributed data. + + The sample code is as follows: + + ``` + class MyObserver : public RdbStoreObserver { + public: + void OnChange(const std::vector& devices) override { + for (const auto& device : devices) { + LOGI("device=%s data change", device.c_str()); + } + } + }; + + SubscribeOption option; + option.mode = SubscribeMode::REMOTE; + MyObserver observer; + store->Subscribe(option, &observer); // Subscribe to distributed data. + + store->UnSubscribe(option, &observer); // Unsubscribe from distributed data. + ``` + +7. Query data across devices. + + a. Obtain the distributed table name for a remote device based on the local table name. + + b. Run SQL statements to query data in the RDB store of the remote device. + + The sample code is as follows: + ``` + std::string tableName = store->ObtainDistributedTableName("123456789abcd", "test"); + auto resultSet = store->QuerySql("SELECT * from ?;", tableName); + ``` diff --git a/zh-cn/application-dev/media/audio-playback.md b/zh-cn/application-dev/media/audio-playback.md index 757d99fdc6ca84fc2aab9acf1d36531a5a46df70..a142a8b010630fa19349c78e8b40bfd956042695 100644 --- a/zh-cn/application-dev/media/audio-playback.md +++ b/zh-cn/application-dev/media/audio-playback.md @@ -25,6 +25,9 @@ AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../reference/apis/js-apis-media.md#audioplayer_属性) ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 console.info('audio set source success'); @@ -80,7 +83,18 @@ function printfDescription(obj) { let audioPlayer = media.createAudioPlayer(); SetCallBack(audioPlayer); //设置事件回调 //2、用户选择音频,设置uri -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调 +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 //3、播放音频 audioPlayer.play(); //需等待'dataLoad'事件回调完成后,才可调用play进行播放,触发'play'事件回调 //4、跳转播放位置 @@ -111,6 +125,9 @@ audioPlayer = undefined; ### 正常播放场景 ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 console.info('audio set source success'); @@ -128,13 +145,27 @@ function SetCallBack(audioPlayer) { let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 SetCallBack(audioPlayer); //设置事件回调 -/* 用户选择音频,设置uri */ -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调 +/* 用户选择视频设置fd(本地播放) */ +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 ``` ### 切歌场景 ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 console.info('audio set source success'); @@ -152,16 +183,42 @@ function SetCallBack(audioPlayer) { let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 SetCallBack(audioPlayer); //设置事件回调 -/* 用户选择音频,设置uri */ -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调 +/* 用户选择视频设置fd(本地播放) */ +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 /* 播放一段时间后,下发切歌指令 */ audioPlayer.reset(); -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/next.mp3'; + +/* 用户选择视频设置fd(本地播放) */ +let fdNextPath = 'fd://' +let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(nextPath).then(fdNumber) => { + fdNextPath = fdNextPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdNextPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); +audioPlayer.src = fdNextPath; ``` ### 单曲循环场景 ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 console.info('audio set source success'); @@ -179,7 +236,19 @@ function SetCallBack(audioPlayer) { let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 SetCallBack(audioPlayer); //设置事件回调 -/* 用户选择音频,设置uri */ -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调 -audioPlayer.loop = true; //设置循环播放属性 + +/* 用户选择视频设置fd(本地播放) */ +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 +audioPlayer.loop = true; //设置循环播放属性 ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-recorder.md b/zh-cn/application-dev/media/audio-recorder.md index 58135f20fe4e66471013c0465c865f934c005881..8c2bc3b74cb0e5ffee65fc4d62cc095e44273626 100644 --- a/zh-cn/application-dev/media/audio-recorder.md +++ b/zh-cn/application-dev/media/audio-recorder.md @@ -23,6 +23,11 @@ 包含流程:创建实例,设置录制参数,录制音频,暂停录制,恢复录制,停止录制,释放资源等流程。 ```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + function SetCallBack(audioRecorder) { audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 console.log('prepare success'); @@ -57,6 +62,31 @@ function SetCallBack(audioRecorder) { }); } +// pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp3 +// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp3'); + // 1.创建实例 let audioRecorder = media.createAudioRecorder(); // 2.设置回调 @@ -68,7 +98,7 @@ let audioRecorderConfig = { audioSampleRate : 22050, numberOfChannels : 2, format : media.AudioOutputFormat.AAC_ADTS, - uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // 文件需先由调用者创建,并给予适当的权限 + uri : testFdNumber, // testFdNumber由getFd生成 location : { latitude : 30, longitude : 130}, } audioRecorder.prepare(audioRecorderConfig); @@ -92,7 +122,12 @@ audioRecorder = undefined; 与全流程场景不同,不包括暂停录制,恢复录制的过程。 ```js -function SetCallBack(audioRecorder) { +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + +function SetCallBack(audioPlayer) { audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 console.log('prepare success'); // 录制界面可切换至已准备好,可点击录制按钮进行录制 @@ -108,6 +143,32 @@ function SetCallBack(audioRecorder) { console.log('audio recorder release success'); }); } + +// pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp3 +// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp3'); + // 1.创建实例 let audioRecorder = media.createAudioRecorder(); // 2.设置回调 @@ -119,7 +180,7 @@ let audioRecorderConfig = { audioSampleRate : 22050, numberOfChannels : 2, format : media.AudioOutputFormat.AAC_ADTS, - uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // 文件需先由调用者创建,并给予适当的权限 + uri : testFdNumber, // testFdNumber由getFd生成 location : { latitude : 30, longitude : 130}, } audioRecorder.prepare(audioRecorderConfig) diff --git a/zh-cn/application-dev/media/video-playback.md b/zh-cn/application-dev/media/video-playback.md index 5fe625c1dfb1e1b29f3f009fdb42ea96ab9a5c30..cecce9c3b62fabfbc187f71fe678db5f487b531c 100644 --- a/zh-cn/application-dev/media/video-playback.md +++ b/zh-cn/application-dev/media/video-playback.md @@ -30,10 +30,21 @@ VideoPlayer支持的url媒体源输入类型可参考:[url属性说明](../reference/apis/js-apis-media.md#videoplayer_属性) +Xcomponent创建方法可参考:[Xcomponent创建方法](#Xcomponent创建方法) + ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // 函数调用发生错误时用于上报错误信息 function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -67,10 +78,19 @@ await media.createVideoPlayer().then((video) => { } }, failureCallback).catch(catchCallback); -// 用户选择视频设置url -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// 用户选择视频设置fd(本地播放) +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中 +videoPlayer.url = fdPath; // 设置surfaceID用于显示视频画面 await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -147,9 +167,18 @@ surfaceID = undefined; ### 正常播放场景 ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // 函数调用发生错误时用于上报错误信息 function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -191,10 +220,19 @@ await media.createVideoPlayer().then((video) => { // 设置事件回调 SetCallBack(videoPlayer); -// 用户选择视频设置url -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// 用户选择视频设置fd(本地播放) +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中 +videoPlayer.url = fdPath; // 设置surfaceID用于显示视频画面 await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -215,9 +253,18 @@ await videoPlayer.play().then(() => { ### 切视频场景 ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // 函数调用发生错误时用于上报错误信息 function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -259,10 +306,19 @@ await media.createVideoPlayer().then((video) => { // 设置事件回调 SetCallBack(videoPlayer); -// 用户选择视频设置url -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// 用户选择视频设置fd(本地播放) +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中 +videoPlayer.url = fdPath; // 设置surfaceID用于显示视频画面 await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -285,7 +341,19 @@ await videoPlayer.reset().then(() => { console.info('reset success'); }, failureCallback).catch(catchCallback); -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/next.mp4'; +// 用户选择视频设置fd(本地播放) +let fdNextPath = 'fd://' +let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.mp4'; +await fileIO.open(nextPath).then(fdNumber) => { + fdNextPath = fdNextPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdNextPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +videoPlayer.url = fdNextPath; // 设置surfaceID用于显示视频画面 await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -306,9 +374,18 @@ await videoPlayer.play().then(() => { ### 单个视频循环场景 ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // 函数调用发生错误时用于上报错误信息 function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -350,10 +427,19 @@ await media.createVideoPlayer().then((video) => { // 设置事件回调 SetCallBack(videoPlayer); -// 用户选择视频设置url -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// 用户选择视频设置fd(本地播放) +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中 +videoPlayer.url = fdPath; // 设置surfaceID用于显示视频画面 await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -372,4 +458,17 @@ videoPlayer.loop = true; await videoPlayer.play().then(() => { console.info('play success'); }, failureCallback).catch(catchCallback); -``` \ No newline at end of file +``` + +### Xcomponent创建方法 + +播放视频中获取surfaceID依赖了Xcomponent,需要创建一个和xxx.js同名的xxx.hml文件,xxx.hml里面需要添加如下代码: + +```js + // 设置窗口宽高等属性 + +``` diff --git a/zh-cn/application-dev/media/video-recorder.md b/zh-cn/application-dev/media/video-recorder.md index 7f7915856da2be8dfd680abb112a6ed7cdd8e4ce..fe104cfd0181ff018c8bf43ba5043b06729f43d8 100644 --- a/zh-cn/application-dev/media/video-recorder.md +++ b/zh-cn/application-dev/media/video-recorder.md @@ -23,6 +23,36 @@ 包含流程:创建实例,设置录制参数,录制视频,暂停录制,恢复录制,停止录制,释放资源等流程。 ```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + +// pathName是传入的录制文件名,例如:01.mp4,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp4 +// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp4'); + let videoProfile = { audioBitrate : 48000, audioChannels : 2, @@ -40,7 +70,7 @@ let videoConfig = { audioSourceType : 1, videoSourceType : 0, profile : videoProfile, - url : 'file:///data/media/01.mp4', + url : testFdNumber, // testFdNumber由getFd生成 orientationHint : 0, location : { latitude : 30, longitude : 130 }, } @@ -61,6 +91,7 @@ function catchCallback(error) { let videoRecorder = null; // videoRecorder空对象在createVideoRecorder成功后赋值 let surfaceID = null; // 用于保存getInputSurface返回的surfaceID + // 创建videoRecorder对象 await media.createVideoRecorder().then((recorder) => { console.info('case createVideoRecorder called'); diff --git a/zh-cn/application-dev/quick-start/Readme-CN.md b/zh-cn/application-dev/quick-start/Readme-CN.md index e530b16bc6e1c2794e9a13a95ad0b41dad140fee..c3104c0b74b7176584af8df66611c0f6938931db 100755 --- a/zh-cn/application-dev/quick-start/Readme-CN.md +++ b/zh-cn/application-dev/quick-start/Readme-CN.md @@ -9,4 +9,11 @@ - [通过导入Sample方式创建新工程](import-sample-to-create-project.md) - [配置OpenHarmony应用签名信息](configuring-openharmony-app-signature.md) - [安装运行OpenHarmony应用](installing-openharmony-app.md) +- 快速入门 + - [前言](start-overview.md) + - [使用eTS语言开发](start-with-ets.md) + - [使用JS语言开发(传统代码方式)](start-with-js.md) + - [使用JS语言开发(低代码方式)](start-with-js-low-code.md) - [包结构说明](package-structure.md) +- [资源文件的分类](basic-resource-file-categories.md) + diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215029852.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215029852.png new file mode 100644 index 0000000000000000000000000000000000000000..fa229933bd2e38a0967750e39b2a2c1f5e80b873 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215029852.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215066868.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215066868.png new file mode 100644 index 0000000000000000000000000000000000000000..d3afe4570f4a839aaa531dea2b1889f318c81f71 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215066868.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215206886.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215206886.png new file mode 100644 index 0000000000000000000000000000000000000000..a1125b97170e8a607515c46610b0d08c5e14b410 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215206886.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215226858.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215226858.png new file mode 100644 index 0000000000000000000000000000000000000000..e2444e0c8488f6632a098585409352a8ce8c7303 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215226858.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215227618.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215227618.png new file mode 100644 index 0000000000000000000000000000000000000000..d3afe4570f4a839aaa531dea2b1889f318c81f71 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215227618.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215386842.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215386842.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215386842.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215388136.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215388136.png new file mode 100644 index 0000000000000000000000000000000000000000..890e12eee8b4534a2b94206c6b73edc81d1ee3ee Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215388136.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215388262.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215388262.png new file mode 100644 index 0000000000000000000000000000000000000000..890e12eee8b4534a2b94206c6b73edc81d1ee3ee Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001215388262.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216084724.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216084724.png new file mode 100644 index 0000000000000000000000000000000000000000..a52947400f005bbdb10141626f3fa1982abcb429 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216084724.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216239356.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216239356.png new file mode 100644 index 0000000000000000000000000000000000000000..4d03d2b8a97319efa04c6c94b394291701371a35 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216239356.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216269940.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216269940.png new file mode 100644 index 0000000000000000000000000000000000000000..d2f276bc812f19e6b92cb299222218d1157f512d Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216269940.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216288558.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216288558.png new file mode 100644 index 0000000000000000000000000000000000000000..0ce709ba3c03c1331c44ebe259aaa8102c160d18 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216288558.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216446670.gif b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216446670.gif new file mode 100644 index 0000000000000000000000000000000000000000..5a7b05bfcdeb8063c3a0c16dae62f3f7168f783d Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216446670.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216448880.gif b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216448880.gif new file mode 100644 index 0000000000000000000000000000000000000000..bc9bca615d9243ccb1121983f66ba30a8b9e3b05 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216448880.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216600980.gif b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216600980.gif new file mode 100644 index 0000000000000000000000000000000000000000..36e9929bd55f02e8737346709a8a2427723614ac Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216600980.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216614132.gif b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216614132.gif new file mode 100644 index 0000000000000000000000000000000000000000..14709a48539ea940ae74ae9c3a4a4e569a4d3b75 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216614132.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216618320.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216618320.png new file mode 100644 index 0000000000000000000000000000000000000000..d8d1420760cc657bf7a4928d01be701c1ea6cb24 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216618320.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216753776.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216753776.png new file mode 100644 index 0000000000000000000000000000000000000000..5e6825c63fe0c733d72526a44a78a1deae32cc94 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001216753776.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217047316.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217047316.png new file mode 100644 index 0000000000000000000000000000000000000000..6c1ea01d448434e7cfd94e174474e72b57d3b4cc Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217047316.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217063248.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217063248.png new file mode 100644 index 0000000000000000000000000000000000000000..25ecf03e7113970dc2c43306ed9d423fa88d97fa Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217063248.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217365030.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217365030.png new file mode 100644 index 0000000000000000000000000000000000000000..c93286ed075c7ea61f21331edc6fdaf575804d97 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217365030.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217384890.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217384890.png new file mode 100644 index 0000000000000000000000000000000000000000..84d5fb3fe5c703c5605358c2ca9d1c6e8ed565f8 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217384890.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217526428.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217526428.png new file mode 100644 index 0000000000000000000000000000000000000000..241ddfa8b9c3a29f5a410c454458471bfa004ee8 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217526428.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217527892.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217527892.png new file mode 100644 index 0000000000000000000000000000000000000000..d2f276bc812f19e6b92cb299222218d1157f512d Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217527892.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217527948.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217527948.png new file mode 100644 index 0000000000000000000000000000000000000000..c93286ed075c7ea61f21331edc6fdaf575804d97 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001217527948.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259866741.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259866741.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259866741.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259949659.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259949659.png new file mode 100644 index 0000000000000000000000000000000000000000..fa229933bd2e38a0967750e39b2a2c1f5e80b873 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259949659.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259987441.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259987441.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001259987441.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260106745.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260106745.png new file mode 100644 index 0000000000000000000000000000000000000000..d3afe4570f4a839aaa531dea2b1889f318c81f71 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260106745.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260107497.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260107497.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260107497.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260189591.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260189591.png new file mode 100644 index 0000000000000000000000000000000000000000..fa229933bd2e38a0967750e39b2a2c1f5e80b873 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260189591.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260226691.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260226691.png new file mode 100644 index 0000000000000000000000000000000000000000..6d8b4f343d3744e245a656987a85a6da2c9bb18e Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260226691.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260227453.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260227453.png new file mode 100644 index 0000000000000000000000000000000000000000..d3afe4570f4a839aaa531dea2b1889f318c81f71 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260227453.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260684127.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260684127.png new file mode 100644 index 0000000000000000000000000000000000000000..241ddfa8b9c3a29f5a410c454458471bfa004ee8 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260684127.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260928361.gif b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260928361.gif new file mode 100644 index 0000000000000000000000000000000000000000..43a0ab27545eb4f8095eec4bbb9490607317f05d Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001260928361.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261017331.gif b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261017331.gif new file mode 100644 index 0000000000000000000000000000000000000000..240e9fb76b0f27d35d53b5b1bd304e39fc80aaf5 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261017331.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261129245.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261129245.png new file mode 100644 index 0000000000000000000000000000000000000000..b774bd7ee5c548fe6ba8b8924f302b5dc7b65b07 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261129245.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261137889.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261137889.png new file mode 100644 index 0000000000000000000000000000000000000000..2821c2b055c71abd5ba1d74201c1c4ab9ddd6647 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261137889.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261142799.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261142799.png new file mode 100644 index 0000000000000000000000000000000000000000..b0fe41acdfae007d26b79e6539d1432be4d420db Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261142799.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261233671.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261233671.png new file mode 100644 index 0000000000000000000000000000000000000000..20bc9853976a1d8b967da762ef88028ee029e150 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261233671.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261233695.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261233695.png new file mode 100644 index 0000000000000000000000000000000000000000..fa80cdac31d31207b21dbd33072a82c015a002be Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261233695.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261786055.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261786055.png new file mode 100644 index 0000000000000000000000000000000000000000..c54739143282ad99334f366d35f2b1696d773f92 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261786055.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261809595.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261809595.png new file mode 100644 index 0000000000000000000000000000000000000000..1ecab0a42fddf058c6c4199070f229a6037881ae Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261809595.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261979271.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261979271.png new file mode 100644 index 0000000000000000000000000000000000000000..12978dc861aaa1f826404d9c6838bb8628381615 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001261979271.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262127855.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262127855.png new file mode 100644 index 0000000000000000000000000000000000000000..b0fe41acdfae007d26b79e6539d1432be4d420db Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262127855.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262206247.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262206247.png new file mode 100644 index 0000000000000000000000000000000000000000..6c1ea01d448434e7cfd94e174474e72b57d3b4cc Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262206247.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262207811.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262207811.png new file mode 100644 index 0000000000000000000000000000000000000000..6c1ea01d448434e7cfd94e174474e72b57d3b4cc Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262207811.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262219043.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262219043.png new file mode 100644 index 0000000000000000000000000000000000000000..12978dc861aaa1f826404d9c6838bb8628381615 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262219043.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262327095.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262327095.png new file mode 100644 index 0000000000000000000000000000000000000000..c93286ed075c7ea61f21331edc6fdaf575804d97 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262327095.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262339067.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262339067.png new file mode 100644 index 0000000000000000000000000000000000000000..12978dc861aaa1f826404d9c6838bb8628381615 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001262339067.png differ diff --git a/zh-cn/application-dev/quick-start/start-overview.md b/zh-cn/application-dev/quick-start/start-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..a5e0cc1f622b326e7977f157384a2a592a539173 --- /dev/null +++ b/zh-cn/application-dev/quick-start/start-overview.md @@ -0,0 +1,47 @@ +# 前言 + + +本文档适用于OpenHarmony应用开发的初学者。通过构建一个简单的具有页面跳转/返回功能的应用(如下图所示),快速了解工程目录的主要文件,熟悉OpenHarmony应用开发流程。 + + +![zh-cn_image_0000001261809595](figures/zh-cn_image_0000001261809595.png) + + +在开始之前,您需要了解有关OpenHarmony应用的一些基本概念:UI框架的简单说明、Ability的基本概念。 + + +## 基本概念 + + +### UI框架 + +OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架)。方舟开发框架可为开发者提供进行应用UI开发时所必须的能力,比如多种组件、布局计算、动画能力、UI交互、绘制等等。 + +方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于JS扩展的类Web开发范式(简称“类Web开发范式”)和基于TS扩展的声明式开发范式(简称“声明式开发范式”)。以下是两种开发范式的简单对比。 + + | **开发范式名称** | **语言生态** | **UI更新方式** | **适用场景** | **适用人群** | +| -------- | -------- | -------- | -------- | -------- | +| 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的类小程序应用和卡片 | Web前端开发人员 | +| 声明式开发范式 | 扩展的TS语言(eTS) | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 | + +对于DevEco Studio V2.2 Beta1及更高版本,在使用JS语言开发时,除传统代码方式外,还支持使用低代码方式。OpenHarmony低代码开发方式,具有丰富的UI界面编辑功能,遵循[JS开发规范](https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-overview-0000001056361791),通过可视化界面开发方式快速构建布局,可有效降低用户的上手成本并提升用户构建UI界面的效率。 + + +### Ability + +[Ability](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ability/ability-brief.md)是应用所具备能力的抽象,也是应用程序的重要组成部分。一个应用可以具备多种能力(即可以包含多个Ability)。OpenHarmony支持应用以Ability为单位进行部署。 + +Ability可以分为[FA(Feature Ability)](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/glossary/glossary.md#f)和[PA(Particle Ability)](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/glossary/glossary.md#p)两种类型,每种类型为开发者提供了不同的模板,以便实现不同的业务功能。其中,FA支持[Page Ability](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ability/fa-pageability.md)模板,以提供与用户交互的能力。一个Page Ability可以含有一个或多个页面(即Page),Page Ability与Page的关系如下图所示: + +![zh-cn_image_0000001215206886](figures/zh-cn_image_0000001215206886.png) + +快速入门提供了一个含有两个页面的Page Ability实例。更多Ability的开发内容及指导,请参见[Ability](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ability/ability-brief.md)。 + + +## 工具准备 + +1. 安装最新版[DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta)。 + +2. 请参考[[配置OpenHarmony SDK](configuring-openharmony-sdk.md)](zh-cn_topic_0000001113561194.xml),完成**DevEco Studio**的安装和开发环境配置。 + +完成上述操作及基本概念的理解后,可参照[使用eTS语言开发](start-with-ets.md)、[使用JS语言开发(传统代码方式)](start-with-js.md)、[使用JS语言开发(低代码方式)](start-with-js-low-code.md)中的任一章节进行下一步体验和学习。 diff --git a/zh-cn/application-dev/quick-start/start-with-ets.md b/zh-cn/application-dev/quick-start/start-with-ets.md new file mode 100644 index 0000000000000000000000000000000000000000..7132e0a0f13f4c56878ed31a8bd8a4c2daa147bd --- /dev/null +++ b/zh-cn/application-dev/quick-start/start-with-ets.md @@ -0,0 +1,244 @@ +# 使用eTS语言开发 + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 请使用**DevEco Studio V3.0.0.601 Beta1**及更高版本。 +> +> 为确保运行效果,本文以使用**DevEco Studio V3.0.0.900 Beta2**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta)获取下载链接。 + + +## 创建eTS工程 + +1. 打开**DevEco Studio**,点击**File** > **New > Create Project**,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 + ![zh-cn_image_0000001260189591](figures/zh-cn_image_0000001260189591.png) + +2. 进入配置工程界面,**UI Syntax**选择“**eTS**”,其他参数保持默认设置即可。 + ![zh-cn_image_0000001217063248](figures/zh-cn_image_0000001217063248.png) + +3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 + + +## eTS工程项目文件 + +- **entry:**OpenHarmony工程模块,编译构建生成一个Hap包。 + - **entry > src > main > ets**:用于存放ets源码。 + - **entry > src >main > ets > MainAbility:**应用/服务的入口。 + - **entry > src >main > ets > MainAbility > pages:**MainAbility包含的页面。 + - **entry > src >main > ets > MainAbility > app.ets**:承载Ability生命周期。 + - **entry > src > main > resources:**用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。 + - **entry > src > main >config.json:**模块配置文件。主要包含HAP包的配置信息、应用在具体设备上的配置信息以及应用的全局配置信息。 + - **entry > build-profile.json5:**模块的模块信息 、编译信息配置项,包括 buildOption target配置等。 + - **entry > hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 + +- **build-profile.json5:**应用级配置信息,包括签名、产品配置等。 + +- **hvigorfile.js:**应用级编译构建任务脚本。 + + +## 构建第一个页面 + +1. **文本组件。** + 工程同步完成后,在“**Project**”窗口,点击“**entry > src > main > ets > MainAbility > pages**”,打开“**index.ets**”文件,可以看到页面由Text组件组成。“**index.ets**”文件的示例如下: + + + ``` + @Entry + @Component + struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } + } + ``` + +2. **添加按钮。** + 在默认页面基础上,我们添加一个Button组件,作为按钮接受用户点击的动作,从而实现跳转到另一个页面。“**index.ets**”文件的示例如下: + + + ``` + @Entry + @Component + struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + // 添加按钮,以接受用户点击 + Button(){ + Text('Next') + .fontSize(30) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top:20 + }) + .backgroundColor('#0D9FFB') + .width('40%') + .height('5%') + } + .width('100%') + } + .height('100%') + } + } + ``` + +3. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。**第一个页面效果如下图所示: + ![zh-cn_image_0000001216239356](figures/zh-cn_image_0000001216239356.png) + + +## 构建第二个页面 + +1. **创建第二个页面。** + 在“**Project**”窗口,打开“**entry > src > main > ets > MainAbility**”,右键点击“**pages**”文件夹,选择“**New > Page**”,命名为“**second**”,点击“**Finish**”,即完成第二个页面的创建。可以看到文件目录结构如下: + + ![zh-cn_image_0000001261233671](figures/zh-cn_image_0000001261233671.png) + +2. **添加文本及按钮。** + 参照第一个页面,在第二个页面添加Text组件、Button组件等,并设置其样式。“**second.ets**”文件的示例如下: + + + ``` + @Entry + @Component + struct Second { + @State message: string = 'Hi there' + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('Back') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('40%') + .height('5%') + } + .width('100%') + } + .height('100%') + } + } + ``` + + +## 实现页面间的跳转 + +页面间的导航可以通过页面路由router来实现。页面路由router根据页面uri找到目标页面,从而实现跳转。使用页面路由请导入router模块。 + +1. **第一个页面跳转到第二个页面。** + 在第一个页面中,跳转按钮绑定onClick方法,当按钮点击时触发页面路由变化,跳转到第二页。“**index.ets**”文件的示例如下: + + + ``` + import router from '@system.router'; + + @Entry + @Component + struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + // 添加按钮,以接受用户点击 + Button(){ + Text('Next') + .fontSize(30) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top:20 + }) + .backgroundColor('#0D9FFB') + .width('40%') + .height('5%') + // 跳转按钮绑定onClicke方法,点击时触发页面路由变化,跳转到第二页 + .onClick(()=>{ + router.push({uri:'pages/second'}) + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +2. **第二个页面返回到第一个页面。** + 在第二个页面中,返回按钮绑定onClick方法,当按钮点击时触发页面路由返回,返回到第一页。“**second.ets**”文件的示例如下: + + + ``` + import router from '@system.router'; + + @Entry + @Component + struct Second { + @State message: string = 'Hi there' + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('Back') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('40%') + .height('5%') + // 返回按钮绑定onClicke方法,点击时触发页面返回,返回到第一页 + .onClick(()=>{ + router.back() + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +3. **打开index.ets文件,点击预览器中的**![zh-cn_image_0000001262219043](figures/zh-cn_image_0000001262219043.png)**按钮进行刷新。**效果如下图所示: + ![zh-cn_image_0000001260684127](figures/zh-cn_image_0000001260684127.png) + + +## 使用真机运行应用 + +1. 将搭载OpenHarmony标准系统的开发板与电脑连接。 + +2. 点击**File >Project Structure** > **Project > Signing**界面勾选“**Automatically generate signing**”,等待自动签名完成即可,点击“**OK**”。如下图所示: + ![zh-cn_image_0000001217365030](figures/zh-cn_image_0000001217365030.png) + +3. **在编辑窗口右上角的工具栏,点击**![zh-cn_image_0000001262206247](figures/zh-cn_image_0000001262206247.png)**按钮运行。**效果如下图所示: + ![zh-cn_image_0000001217526428](figures/zh-cn_image_0000001217526428.png) diff --git a/zh-cn/application-dev/quick-start/start-with-js-low-code.md b/zh-cn/application-dev/quick-start/start-with-js-low-code.md new file mode 100644 index 0000000000000000000000000000000000000000..69fad51d668aae55c16086184521287948800519 --- /dev/null +++ b/zh-cn/application-dev/quick-start/start-with-js-low-code.md @@ -0,0 +1,155 @@ +# 使用JS语言开发(低代码方式) + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 该特性在**DevEco Studio V2.2 Beta1**及更高版本中支持。 +> +> 为确保运行效果,本文以使用**DevEco Studio V3.0.0.900 Beta2**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta)获取下载链接。 + + +OpenHarmony低代码开发方式,具有丰富的UI界面编辑功能,遵循[JS开发规范](https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-overview-0000001056361791),通过可视化界面开发方式快速构建布局,可有效降低用户的上手成本并提升用户构建UI界面的效率。 + + +使用低代码开发应用或服务有以下两种开发方式: + + +- 直接创建一个支持低代码开发的新工程以进行开发。本文以此方式为例进行说明。 + +- 在已有工程中,创建Visual文件来进行开发。 + + +## 创建新工程支持低代码开发 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 该功能在DevEco Studio 3.0 Beta2及更高版本中支持,且compileSdkVersion必须为7或以上。 + +1. 打开**DevEco Studio**,点击**File** > **New > Create Project**,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 + ![zh-cn_image_0000001259949659](figures/zh-cn_image_0000001259949659.png) + +2. 进入配置工程界面,打开“**Super Visual Enable**”开关**,UI Syntax**选择“**JS**”,其他参数保持默认设置即可。 + ![zh-cn_image_0000001261786055](figures/zh-cn_image_0000001261786055.png) + +3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 + + +## 低代码开发工程项目文件 + +工程同步完成后,自动生成以下目录结构: + +![zh-cn_image_0000001216753776](figures/zh-cn_image_0000001216753776.png) + +- **pages > index > index.js**:低代码页面的逻辑描述文件,定义了页面里所用到的所有的逻辑关系,比如数据、事件等,详情请参考[JS语法参考](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/js-framework-syntax-js-0000000000611432)。如果创建了多个低代码页面,则pages目录下会生成多个页面文件夹及对应的js文件。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > 使用低代码页面开发时,其关联js文件的同级目录中不能包含hml和css页面,例如上图中的**js > MainAbility > pages > index**目录下不能包含hml与css文件,否则会出现编译报错。 + +- **pages > index > index.visual**:visual文件存储低代码页面的数据模型,双击该文件即可打开低代码页面,进行可视化开发设计。如果创建了多个低代码页面,则pages目录下会生成多个页面文件夹及对应的visual文件。 + + +## 构建第一个页面 + +工程同步完成后,第一个页面已有一个容器、文本(Hello World)显示。为了更详细地了解低代码开发,我们将删除画布原有模板组件,从零开始完成页面的添加、设置。 + +第一个页面内有一个容器、文本和一个按钮,通过Div、Text和Button组件来实现。 + +1. **删除画布原有模板组件。** + 打开index.visual文件,选中画布中的组件,单击鼠标右键,选择Delete删除画布原有模板组件。操作如下所示: + + ![zh-cn_image_0000001216600980](figures/zh-cn_image_0000001216600980.gif) + +2. **添加容器,设置Div容器的样式和属性。** + 选中UI Control中的Div组件,将其拖至画布。点击右侧属性样式栏中的样式图标![zh-cn_image_0000001260226691](figures/zh-cn_image_0000001260226691.png)(General),设置Div组件的高度Height为100%,使其占满屏幕;点击右侧属性样式栏中的样式图标![zh-cn_image_0000001215226858](figures/zh-cn_image_0000001215226858.png)(Flex),设置Div组件的FlexDirection样式为column,使Div的主轴垂直;设置Div组件的JustifyContent样式为center,使得其子组件在主轴上居中显示;设置Div组件的AlignItems样式为center,使得其子组件在交叉轴上居中显示。操作如下所示: + + ![zh-cn_image_0000001216448880](figures/zh-cn_image_0000001216448880.gif) + +3. **添加文本。** + 选中UI Control中的Text组件,将其拖至Div组件的中央区域。点击右侧属性样式栏中的属性图标![zh-cn_image_0000001215066868](figures/zh-cn_image_0000001215066868.png)(Properties),设置Text组件的Content属性为“Hello World”;点击右侧属性样式栏中的样式图标![zh-cn_image_0000001215386842](figures/zh-cn_image_0000001215386842.png)(Feature),设置组件的FontSize样式为60px,使得其文字放大;设置组件的TextAlign样式为center,使得组件文字居中显示。再选中画布上的Text组件,拖动放大。操作如下所示: + + ![zh-cn_image_0000001216446670](figures/zh-cn_image_0000001216446670.gif) + +4. **添加按钮。** + 选中UI Control中的Button组件,将其拖至Text组件下面。点击右侧属性样式栏中的属性图标![zh-cn_image_0000001260106745](figures/zh-cn_image_0000001260106745.png)(Properties),设置Button组件的Value属性为“Next”,点击右侧属性样式栏中的样式图标![zh-cn_image_0000001259866741](figures/zh-cn_image_0000001259866741.png)(Feature),设置组件的FontSize样式为40px,使得其文字放大;再选中画布上的Button组件,拖动放大。操作如下所示: + + ![zh-cn_image_0000001260928361](figures/zh-cn_image_0000001260928361.gif) + +5. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。**第一个页面效果如下图所示: + ![zh-cn_image_0000001216288558](figures/zh-cn_image_0000001216288558.png) + + +## 构建第二个页面 + +1. **创建第二个页面。** + 在“**Project**”窗口,打开“**entry > src > main > js > MainAbility**”,右键点击“**pages**”文件夹,选择“**New > Visual**”,命名为“**second**”,单击“**Finish**”,即完成第二个页面的创建。可以看到文件目录结构如下: + + ![zh-cn_image_0000001261129245](figures/zh-cn_image_0000001261129245.png) + +2. **[删除画布原有模板组件。](#delete_origin_content)** + +3. **[添加容器,设置Div容器的样式和属性](#add_container)** + +4. **添加文本。** + 选中Text组件,拖至Div组件的中央区域。点击右侧属性样式栏中的属性图标![zh-cn_image_0000001260227453](figures/zh-cn_image_0000001260227453.png)(Properties),设置Text组件的Content属性为“Hi there”;点击右侧属性样式栏中的样式图标![zh-cn_image_0000001260107497](figures/zh-cn_image_0000001260107497.png)(Feature),设置组件的FontSize样式为60px;设置组件的TextAlign样式为center。再选中画布上的Text组件,拖动放大。操作如下所示: + + ![zh-cn_image_0000001216614132](figures/zh-cn_image_0000001216614132.gif) + +5. **添加按钮。** + 选中UI Control中的Button组件,将其拖至Text组件下面。点击右侧属性样式栏中的属性图标![zh-cn_image_0000001215227618](figures/zh-cn_image_0000001215227618.png)(Properties),设置Button组件的Value属性为“Back”,点击右侧属性样式栏中的样式图标![zh-cn_image_0000001259987441](figures/zh-cn_image_0000001259987441.png)(Feature),设置组件的FontSize样式为40px,使得其文字放大;再选中画布上的Button组件,拖动放大。操作如下所示: + + ![zh-cn_image_0000001261017331](figures/zh-cn_image_0000001261017331.gif) + + +## 实现页面间的跳转 + +页面间的导航可以通过[页面路由router](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ui-js-building-ui-routes.md)来实现。页面路由router根据页面uri找到目标页面,从而实现跳转。使用页面路由请导入router模块。 + +1. **第一个页面跳转到第二个页面。** + 在第一个页面中,跳转按钮绑定onclick方法,当按钮点击时触发页面路由变化,跳转到第二页。需同时处理js文件及visual文件。 + - “**index.js**”示例如下: + + ``` + import router from '@system.router'; + + export default { + onclick() { + router.push ({ + uri:'pages/second/second', // 指定要跳转的页面 + }) + } + } + ``` + + - “**index.viusal**”: 打开index.visual,选中画布上的Button组件。点击右侧属性样式栏中的事件图标![zh-cn_image_0000001215388136](figures/zh-cn_image_0000001215388136.png)(Events),鼠标点击Click事件的输入框,选择onclick事件,如下所示: + ![zh-cn_image_0000001261137889](figures/zh-cn_image_0000001261137889.png) + +2. **第二个页面返回到第一个页面。** + 在第二个页面中,返回按钮绑定onClick方法,当按钮点击时触发页面路由返回,返回到第二页。 + + 需同时处理js文件及visual文件。 + + - “**second.js**”示例如下: + + ``` + import router from '@system.router'; + + export default { + back() { + router.back () + } + } + ``` + - “**second.viusal**”: 打开second.visual,选中画布上的Button组件。点击右侧属性样式栏中的事件图标![zh-cn_image_0000001215388262](figures/zh-cn_image_0000001215388262.png)(Events),鼠标点击Click事件的输入框,选择back事件,如下所示: + + ![zh-cn_image_0000001216618320](figures/zh-cn_image_0000001216618320.png) + +3. **打开index.visual或index.js文件,点击预览器中的**![zh-cn_image_0000001261979271](figures/zh-cn_image_0000001261979271.png)**按钮进行刷新。**效果如下图所示: + ![zh-cn_image_0000001261142799](figures/zh-cn_image_0000001261142799.png) + + +## 使用真机运行应用 + +1. 将搭载OpenHarmony标准系统的开发板与电脑连接。 + +2. 点击**File >Project Structure** > **Project > Signing**界面勾选“**Automatically generate signing**”,等待自动签名完成即可,点击“**OK**”。如下图所示: + ![zh-cn_image_0000001217527948](figures/zh-cn_image_0000001217527948.png) + +3. **在编辑窗口右上角的工具栏,点击**![zh-cn_image_0000001262207811](figures/zh-cn_image_0000001262207811.png)**按钮运行。**效果如下图所示: + ![zh-cn_image_0000001262127855](figures/zh-cn_image_0000001262127855.png) diff --git a/zh-cn/application-dev/quick-start/start-with-js.md b/zh-cn/application-dev/quick-start/start-with-js.md new file mode 100644 index 0000000000000000000000000000000000000000..75a45e3bb278c6e76893b808f60e43f2f4a14f8a --- /dev/null +++ b/zh-cn/application-dev/quick-start/start-with-js.md @@ -0,0 +1,200 @@ +# 使用JS语言开发(传统代码方式) + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 为确保运行效果,本文以使用**DevEco Studio V3.0.0.900 Beta2**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta)获取下载链接。 + + +## 创建JS工程 + +1. 打开**DevEco Studio**,点击**File** > **New > Create Project**,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 + ![zh-cn_image_0000001215029852](figures/zh-cn_image_0000001215029852.png) + +2. 进入配置工程界面,**UI Syntax**选择“**JS**”,其他参数保持默认设置即可。 + ![zh-cn_image_0000001217384890](figures/zh-cn_image_0000001217384890.png) + +3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 + + +## JS工程项目文件 + +- **entry:**OpenHarmony工程模块,编译构建生成一个Hap包。 + - **entry > src > main > js**:用于存放js源码。 + - **entry > src >main > js > MainAbility:**应用/服务的入口。 + - **entry > src >main > js > MainAbility > pages:**MainAbility包含的页面。 + - **entry > src >main >js > MainAbility > app.js**:承载Ability生命周期。 + - **entry > src > main > resources:**用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。 + - **entry > src > main > config.json**:模块配置文件。主要包含HAP包的配置信息、应用在具体设备上的配置信息以及应用的全局配置信息。 + - **entry > build-profile.json5:**模块的模块信息 、编译信息配置项,包括 buildOption target配置等。 + - **entry > hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 + +- **build-profile.json5:**应用级配置信息,包括签名、产品配置等。 + +- **hvigorfile.js:**应用级编译构建任务脚本。 + + +## 构建第一个页面 + +1. **文本组件。** + 工程同步完成后,在“**Project**”窗口,点击“**entry > src >main > js > MainAbility > pages> index**”,打开“**index.hml**”文件,设置Text组件内容。“**index.hml**”文件的示例如下: + + + ``` +
+ + Hello World + +
+ ``` + +2. **添加按钮,并绑定onclick方法。** + 在默认页面基础上,我们添加一个button类型的input组件,作为按钮接受用户点击的动作,从而实现跳转到另一个页面。“**index.hml**”文件的示例代码如下: + + + ``` +
+ + Hello World + + + +
+ ``` + +3. **设置页面样式。** + 在“**Project**”窗口,点击“**entry > src >main > js > MainAbility > pages> index**”,打开“**index.css**”文件,可以对页面中文本、按钮设置宽高、字体大小、间距等样式。“**index.css**”文件的示例如下: + + + ``` + .container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 100%; + height: 100%; + } + + .title { + font-size: 100px; + font-weight: bold; + text-align: center; + width: 100%; + margin: 10px; + } + .btn{ + font-size: 60px; + font-weight: bold; + text-align: center; + width: 40%; + height: 5%; + margin-top: 20px; + } + ``` + +4. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。**第一个页面效果如下图所示: + ![zh-cn_image_0000001216084724](figures/zh-cn_image_0000001216084724.png) + + +## 构建第二个页面 + +1. **创建第二个页面。** + 在“**Project**”窗口,打开“**entry > src > main > js > MainAbility**”,右键点击“**pages**”文件夹,选择“**New > Page**”,命名为“**second**”,点击“**Finish**”,即完成第二个页面的创建。可以看到文件目录结构如下: + + ![zh-cn_image_0000001261233695](figures/zh-cn_image_0000001261233695.png) + +2. **添加文本及按钮。** + 参照第一个页面,在第二个页面添加文本、按钮及点击按钮绑定页面返回等。“**second.hml**”文件的示例如下: + + + ``` +
+ + Hi there + + + +
+ ``` + +3. **设置页面样式**。“**second.css**”文件的示例如下: + + ``` + .container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 100%; + height: 100%; + } + + .title { + font-size: 100px; + font-weight: bold; + text-align: center; + width: 100%; + margin: 10px; + } + .btn{ + font-size: 60px; + font-weight: bold; + text-align: center; + width: 40%; + height: 5%; + margin-top: 20px; + } + ``` + + +## 实现页面间的跳转 + +页面间的导航可以通过[页面路由router](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ui-js-building-ui-routes.md)来实现。页面路由router根据页面uri找到目标页面,从而实现跳转。使用页面路由请导入router模块。 + +1. **第一个页面跳转到第二个页面。** + 在第一个页面中,跳转按钮绑定onClick方法,当按钮点击时触发页面路由变化,跳转到第二页。“**index.js**”示例如下: + + + ``` + import router from '@system.router' + + export default { + onclick: function () { + router.push({ + uri: "pages/second/second" + }) + } + } + ``` + +2. **第二个页面返回到第一个页面。** + 在第二个页面中,返回按钮绑定onClick方法,当按钮点击时触发页面路由返回,返回到第二页。“**second.js**”示例如下: + + + ``` + import router from '@system.router' + + export default { + back: function () { + router.back() + } + } + ``` + +3. **打开index文件夹下的任意一个文件,点击预览器中的**![zh-cn_image_0000001262339067](figures/zh-cn_image_0000001262339067.png)**按钮进行刷新。**效果如下图所示: + ![zh-cn_image_0000001216269940](figures/zh-cn_image_0000001216269940.png) + + +## 使用真机运行应用 + +1. 将搭载OpenHarmony标准系统的开发板与电脑连接。 + +2. 点击**File >Project Structure** > **Project > Signing**界面勾选“**Automatically generate signing**”,等待自动签名完成即可,点击“**OK**”。如下图所示: + ![zh-cn_image_0000001262327095](figures/zh-cn_image_0000001262327095.png) + +3. **在编辑窗口右上角的工具栏,点击**![zh-cn_image_0000001217047316](figures/zh-cn_image_0000001217047316.png)**按钮运行。**效果如下图所示: + ![zh-cn_image_0000001217527892](figures/zh-cn_image_0000001217527892.png) diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index ff67949950f6b13b004b7be97cb5da316b074f49..5d76cee874ee31f427f240c8a754aa3db34c76d9 100644 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -25,7 +25,8 @@ - [访问控制](js-apis-abilityAccessCtrl.md) - [通用密钥库系统](js-apis-huks.md) - 数据管理 - - [轻量级存储](js-apis-data-preferences.md) + - [轻量级存储9+](js-apis-data-preferences.md) + - [轻量级存储](js-apis-data-storage.md) - [分布式数据管理](js-apis-distributed-data.md) - [关系型数据库](js-apis-data-rdb.md) - [结果集](js-apis-data-resultset.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md index 9d24c4016b956c5504cf5fdfe6896441a13a9c97..e1333719ff66a34cc1b2c627195fd90e77c62de5 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md +++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md @@ -458,7 +458,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { ## bundle.getAllApplicationInfo -function getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; +function getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; 获取指定用户下所有已安装的应用信息,使用callback形式返回结果。 @@ -490,7 +490,7 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => { }) ``` -``## bundle.getAbilityInfo +## bundle.getAbilityInfo getAbilityInfo(bundleName: string, abilityName: string): Promise\ @@ -750,9 +750,8 @@ SystemCapability.BundleManager.BundleFramework **示例:** ```js -let bundleName : "com.example.myapplication"; -bundle. - +let bundleName = "com.example.myapplication"; +bundle.isApplicationEnabled(bundleName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); }).catch((error) => { @@ -880,7 +879,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { ## bundle.queryAbilityByWant -queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void +queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void 以异步方法根据给定的意图获取Ability信息,使用callback形式返回结果。 @@ -915,7 +914,7 @@ bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { ## bundle.getBundleInstaller -getBundleInstaller(): Promise +getBundleInstaller(): Promise\ 以异步方法获取BundleInstaller,使用Promise形式返回结果。 @@ -931,7 +930,7 @@ SystemCapability.BundleManager.BundleFramework | 类型 | 说明 | | ------------------------ | --------------------------------------------------- | -| Promise | 返回值为Promise对象,Promise中包含BundleInstaller。 | +| Promise\ | 返回值为Promise对象,Promise中包含BundleInstaller。 | **示例:** @@ -958,7 +957,7 @@ bundle.getBundleInstaller() ## bundle.getBundleInstaller -getBundleInstaller(callback: AsyncCallback): void; +getBundleInstaller(callback: AsyncCallback\): void; 以异步方法获取BundleInstaller,使用callback形式返回结果。 @@ -974,7 +973,7 @@ SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 必填 | 描述 | | -------- | ------------------------------ | ---- | ------------------------------------------------- | -| callback | AsyncCallback | 是 | 程序启动作为入参的回调函数,返回BundleInstaller。 | +| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回BundleInstaller。 | **示例:** @@ -1039,7 +1038,7 @@ bundle.getLaunchWantForBundle(bundleName) ## bundle.getLaunchWantForBundle -getLaunchWantForBundle(bundleName: string, callback: AsyncCallback): void; +getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; 以异步方法查询拉起指定应用的want对象,使用callback形式返回结果。 @@ -1107,7 +1106,7 @@ bundle.getNameForUid(uid) ## bundle.getNameForUid -getNameForUid(uid: number, callback: AsyncCallback): void; +getNameForUid(uid: number, callback: AsyncCallback\): void; 以异步方法通过uid获取对应的包名,使用callback形式返回结果。 @@ -1138,9 +1137,9 @@ bundle.getNameForUid(uid, (err, data) => { ## bundle.getAbilityIcon -function getAbilityIcon(bundleName: string, abilityName: string): Promise; +function getAbilityIcon(bundleName: string, abilityName: string): Promise\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>; -以异步方法通过bundleName和abilityName获取对应Icon的PixelMap,使用Promise形式返回结果。 +以异步方法通过bundleName和abilityName获取对应Icon的[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md),使用Promise形式返回结果。 **参数:** @@ -1152,7 +1151,7 @@ function getAbilityIcon(bundleName: string, abilityName: string): Promise | 返回值为PixelMap。 | +| Promise\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)> | 返回值为<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>。 | **示例:** @@ -1169,9 +1168,9 @@ bundle.getAbilityIcon(bundleName, abilityName) ## bundle.getAbilityIcon -function getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback): void; +function getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>): void; -以异步方法通过bundleName和abilityName获取对应的PixelMap,使用callback形式返回结果。 +以异步方法通过bundleName和abilityName获取对应的[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md),使用callback形式返回结果。 **参数:** @@ -1179,7 +1178,7 @@ function getAbilityIcon(bundleName: string, abilityName: string, callback: Async | ---------- | ------ | ---- | -------- | | bundleName | string | 是 | 要查询的bundleName。 | | abilityName | string | 是 | 要查询的abilityName。 | -| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回指定PixelMap。 | +| callback | AsyncCallback\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)> | 是 | 程序启动作为入参的回调函数,返回指定<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>。 | **示例:** @@ -1196,9 +1195,129 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { ``` +## bundle.queryExtensionAbilityInfosByWant + +function queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, userId?: number): Promise> + +以异步方法根据给定的意图获取ExtensionAbility信息,使用Promise形式返回结果。 + +**需要权限:** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO + +**系统能力:** + +SystemCapability.BundleManager.BundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| want | Want | 是 | 包含要查询的应用程序包名称的意图。 | +| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:大于等于0。 | +| userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------- | ---------------------------- | +| Promise> | Promise形式返回ExtensionAbility信息。 | + +**示例:** + +```js +let extensionFlags = 0; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; +bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, userId) +.then((data) => { + console.info('Operation successful. Data: ' + JSON.stringify(data)); +}).catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}) +``` + + + +## bundle.queryExtensionAbilityInfosByWant + +function queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, userId: number, callback: AsyncCallback>): void + +以异步方法根据给定的意图获取ExtensionAbility信息,使用callback形式返回结果。 + +**系统能力:** + +SystemCapability.BundleManager.BundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| want | Want | 是 | 指示包含要查询的应用程序包名称的意图。 | +| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值,大于等于0。 | +| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0 | +| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回ExtensionAbility信息。 | + +**示例:** + +```js +let extensionFlags = 0; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; +bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, userId, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. Data:' + JSON.stringify(data)); +}) +``` + +## bundle.queryExtensionAbilityInfosByWant + +function queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, callback: AsyncCallback>): void; + +以异步方法根据给定的意图获取ExtensionAbility信息,使用callback形式返回结果。 + +**系统能力:** + +SystemCapability.BundleManager.BundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| want | Want | 是 | 指示包含要查询的应用程序包名称的意图。 | +| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:大于等于0。 | +| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回ExtensionAbility信息。 | + +**示例:** + +```js +let extensionFlags = 0; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; +bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. Data:' + JSON.stringify(data)); +}) +``` + + ## ElementName - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 读写属性 | 类型 | 必填 | 描述 | | ----------- | -------- | ------ | ---- | ------------------------------------------------------------ | @@ -1210,7 +1329,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { ## InstallStatus - **系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** SystemCapability.BundleManager.BundleFramework | 名称 | 读写属性 | 类型 | 必填 | 描述 | | ------------- | -------- | ---------------- | ---- | ------------------------------------------------------------ | @@ -1220,7 +1339,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { 包的标志 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 默认值 | 说明 | | ------ | ------ | ------ | @@ -1231,6 +1350,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { | GET_APPLICATION_INFO_WITH_PERMISSION | 0x00000008 | 获取包括权限的应用信息 | | GET_BUNDLE_WITH_REQUESTED_PERMISSION | 0x00000010 | 获取包括所需权限的包信息 | | GET_ABILITY_INFO_WITH_METADATA | 0x00000020 | 获取ability的元数据信息 | +| GET_BUNDLE_WITH_EXTENSION_ABILITY | 0x00000020 | 获取包括Ability信息的扩展包信息 | | GET_APPLICATION_INFO_WITH_METADATA | 0x00000040 | 获取应用的元数据信息 | | GET_ABILITY_INFO_SYSTEMAPP_ONLY | 0x00000080 | 获取仅包括系统应用的ability信息 | | GET_ABILITY_INFO_WITH_DISABLE | 0x00000100 | 获取包括被禁用的ability信息 | @@ -1241,7 +1361,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { 包的选项 - **系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | @@ -1251,7 +1371,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { 应用包的信息 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | @@ -1262,28 +1382,29 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { | installTime | number | 是 | 否 | HAP包安装时间 | | updateTime | number | 是 | 否 | HAP包更新时间 | | appInfo | ApplicationInfo | 是 | 否 | 应用程序的配置信息 | -| abilityInfos | Array | 是 | 否 | Ability的配置信息 | -| reqPermissions | Array | 是 | 否 | 应用运行时需向系统申请的权限集合 | -| reqPermissionDetails | Array | 是 | 否 | 应用运行时需向系统申请的权限集合的详细信息 | +| abilityInfos | Array\ | 是 | 否 | Ability的配置信息 | +| reqPermissions | Array\ | 是 | 否 | 应用运行时需向系统申请的权限集合 | +| reqPermissionDetails | Array\ | 是 | 否 | 应用运行时需向系统申请的权限集合的详细信息 | | vendor | string | 是 | 否 | 应用包的供应商 | | versionCode | number | 是 | 否 | 应用包的版本号 | | versionName | string | 是 | 否 | 应用包的版本文本描述信息 | | compatibleVersion | number | 是 | 否 | 运行应用包所需要最低的SDK版本号 | | targetVersion | number | 是 | 否 | 运行应用包所需要最高SDK版本号 | | isCompressNativeLibs | boolean | 是 | 否 | 是否压缩应用包的本地库,默认为true | -| hapModuleInfos | Array | 是 | 否 | 模块的配置信息 | +| hapModuleInfos | Array\ | 是 | 否 | 模块的配置信息 | | entryModuleName | string | 是 | 否 | Entry的模块名称 | | cpuAbi | string | 是 | 否 | 应用包的cpuAbi信息 | | isSilentInstallation | string | 是 | 否 | 是否通过静默安装 | | minCompatibleVersionCode | number | 是 | 否 | 分布式场景下的应用包兼容的最低版本 | | entryInstallationFree | boolean | 是 | 否 | Entry是否支持免安装 | -| reqPermissionStates | Array | 是 | 否 | 申请权限的授予状态 | +| reqPermissionStates | Array\ | 是 | 否 | 申请权限的授予状态 | +| extensionAbilityInfo | Array\ | 是 | 否 | ability的可扩展信息 | ## ApplicationInfo 应用程序信息 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | @@ -1298,22 +1419,24 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { | iconId | string | 是 | 否 | 应用程序的图标id | | process | string | 是 | 否 | 应用程序的进程,如果不设置,默认为包的名称 | | supportedModes | number | 是 | 否 | 应用程序支持的运行模式 | -| moduleSourceDirs | Array | 是 | 否 | 应用程序的资源存放的相对路径 | -| permissions | Array | 是 | 否 | 访问应用程序所需的权限 | -| moduleInfos | Array | 是 | 否 | 应用程序的模块信息 | +| moduleSourceDirs | Array\ | 是 | 否 | 应用程序的资源存放的相对路径 | +| permissions | Array\ | 是 | 否 | 访问应用程序所需的权限 | +| moduleInfos | Array\ | 是 | 否 | 应用程序的模块信息 | | entryDir | string | 是 | 否 | 应用程序的文件保存路径 | -| customizeData | Map> | 是 | 是 | 应用程序的自定义数据 | +| customizeData | Map> | 是 | 是 | 应用程序的自定义数据 | | codePath | string | 是 | 否 | 应用程序的安装目录 | -| metaData | Map> | 是 | 否 | 应用程序的自定义元信息 | +| metaData | Map> | 是 | 否 | 应用程序的自定义元信息 | +| metaData | Map> | 是 | 否 | 应用程序的元信息 | | removable | boolean | 是 | 否 | 应用程序是否可以被移除 | | accessTokenId | number | 是 | 否 | 应用程序的accessTokenId | | uid | number | 是 | 否 | 应用程序的uid | +| entityType | string | 是 | 否 | 应用程序的实体类型 | ## ModuleInfo 应用程序的模块信息 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | @@ -1324,7 +1447,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { 自定义元数据 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ----- | ------ | ---- | ---- | ---------------- | @@ -1337,7 +1460,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { Hap模块信息 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | @@ -1350,19 +1473,21 @@ Hap模块信息 | iconId | number | 是 | 否 | 模块图标ID | | backgroundImg | string | 是 | 否 | 模块背景图片 | | supportedModes | number | 是 | 否 | 模块支持的模式 | -| reqCapabilities | Array | 是 | 否 | 模块运行需要的能力 | -| deviceTypes | Array | 是 | 否 | 支持运行的设备类型 | -| abilityInfo | Array | 是 | 否 | Ability信息 | +| reqCapabilities | Array\ | 是 | 否 | 模块运行需要的能力 | +| deviceTypes | Array\ | 是 | 否 | 支持运行的设备类型 | +| abilityInfo | Array\ | 是 | 否 | Ability信息 | | moduleName | string | 是 | 否 | 模块名 | | mainAbilityName | string | 是 | 否 | 入口Ability名称 | | installationFree | boolean | 是 | 否 | 是否支持免安装 | | mainElementName | string | 是 | 否 | 入口ability信息 | +| extensionAbilityInfo | Array\ | 是 | 否 | extensionAbility信息 | +| metadata | Array\ | 是 | 否 | Ability的元信息 | ## ReqPermissionDetail 应用运行时需向系统申请的权限集合的详细信息 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | @@ -1374,11 +1499,11 @@ Hap模块信息 描述权限使用的场景和时机 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | -| abilities | Array | 是 | 是 | 使用到该权限的Ability集合 | +| abilities | Array\ | 是 | 是 | 使用到该权限的Ability集合 | | when | string | 是 | 是 | 使用该权限的时机 | @@ -1386,7 +1511,7 @@ Hap模块信息 Ability信息 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ------ | ------ | ------ | @@ -1406,23 +1531,24 @@ Ability信息 | type | AbilityType | 是 | 否 | Ability类型 | | orientation | DisplayOrientation | 是 | 否 | Ability的显示模式 | | launchMode | LaunchMode | 是 | 否 | Ability的启动模式 | -| permissions | Array | 是 | 否 | 被其他应用Ability调用时需要申请的权限集合 | -| deviceTypes | Array | 是 | 否 | Ability支持的设备类型 | -| deviceCapabilities | Array | 是 | 否 | Ability需要的设备能力 | +| permissions | Array\ | 是 | 否 | 被其他应用Ability调用时需要申请的权限集合 | +| deviceTypes | Array\ | 是 | 否 | Ability支持的设备类型 | +| deviceCapabilities | Array\ | 是 | 否 | Ability需要的设备能力 | | readPermission | string | 是 | 否 | 读取Ability数据所需的权限 | | writePermission | string | 是 | 否 | 向Ability写数据所需的权限 | | applicationInfo | ApplicationInfo | 是 | 否 | 应用程序的配置信息 | | uri | string | 是 | 否 | 获取Ability的统一资源标识符(URI) | | labelId | number | 是 | 否 | Ability的标签id | | subType | AbilitySubType | 是 | 否 | Ability中枚举使用的模板的子类型 | -| metaData | Array | 是 | 否 | ability的自定义元信息 | +| metaData | Array\ | 是 | 否 | ability的自定义信息 | +| metaData | Array\ | 是 | 否 | ability的元信息 | | enabled | boolean | 是 | 否 | ability是否可用 | ## AbilityType Ability类型 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 说明 | | ------- | ---- | --------------------------- | @@ -1435,7 +1561,7 @@ Ability类型 屏幕显示方向 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 说明 | | ------------- | ---- | ------------------------ | @@ -1448,7 +1574,7 @@ Ability类型 启动模式 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 说明 | | ----------- | ---- | ------------------- | @@ -1459,9 +1585,79 @@ Ability类型 Ability的子类型 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework | 名称 | 类型 | 说明 | | ----------- | ---- | ----------------------------- | | UNSPECIFIED | 0 | 未定义Ability子类型 | | CA | 1 | Ability子类型是带有 UI 的服务 | + + +## ExtensionAbilityType + +ExtensionAbility的类型 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework + +| 名称 | 类型 | 说明 | +| -------------------- | ---- | ----------------------------- | +| FORM | 0 | ExtensionAbility的类型包括卡片 | +| WORK_SCHEDULER | 1 | ExtensionAbility的类型包括行程安排 | +| INPUT_METHOD | 2 | ExtensionAbility的类型包括输入法 | +| SERVICE | 3 | ExtensionAbility的类型包括服务 | +| ACCESSIBILITY | 4 | ExtensionAbility的类型包括无障碍 | +| DATA_SHARE | 5 | ExtensionAbility的类型包括数据共享 | +| FILE_SHARE | 6 | ExtensionAbility的类型包括文件共享 | +| STATIC_SUBSCRIBER | 7 | ExtensionAbility的类型包括订阅者 | +| WALLPAPER | 8 | ExtensionAbility的类型包括墙纸 | +| UNSPECIFIED | 9 | ExtensionAbility未指定类型 | + +## ExtensionFlag + +扩展标志 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework + +| 名称 | 默认值 | 说明 | +| ------ | ------ | ------ | +| GET_EXTENSION_INFO_DEFAULT | 0x00000000 | 获取默认的extensionAbilityInfo | +| GET_EXTENSION_INFO_WITH_PERMISSION | 0x00000002 | 获取携带权限信息的extensionAbilityInfo | +| GET_EXTENSION_INFO_WITH_APPLICATION | 0x00000004 | 获取携带应用信息的extensionAbilityInfo | +| GET_EXTENSION_INFO_WITH_METADATA | 0x00000020 | 获取携带元数据信息的extensionAbilityInfo | + + +## ExtensionAbilityInfo + +ExtensionAbility信息 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ------ | ------ | ------ | +| bundleName | string | 是 | 否 | 应用包名 | +| moduleName | string | 是 | 否 | ExtensionAbility所属的HAP包的名称 | +| name | string | 是 | 否 | ExtensionAbility名称 | +| labelId | number | 是 | 否 | ExtensionAbility的标签id | +| descriptionId | number | 是 | 否 | ExtensionAbility的描述id | +| iconId | number | 是 | 否 | ExtensionAbility的图标id | +| isVisible | boolean | 是 | 否 | 判断ExtensionAbility是否可以被其他应用调用 | +| extensionAbilityType | bundle.ExtensionAbilityType | 是 | 否 | ExtensionAbility类型 | +| permissions | Array\ | 是 | 否 | 被其他应用ExtensionAbility调用时需要申请的权限集合 | +| applicationInfo | ApplicationInfo | 是 | 否 | 应用程序的配置信息 | +| metaData | Array\ | 是 | 否 | ExtensionAbility的元信息 | +| enabled | boolean | 是 | 否 | ExtensionAbility是否可用 | +| readPermission | string | 是 | 否 | 读取ExtensionAbility数据所需的权限 | +| writePermission | string | 是 | 否 | 向ExtensionAbility写数据所需的权限 | + + +## Metadata + +元数据信息 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | ---------------- | +| name | string | 是 | 是 | 元数据名称 | +| value | string | 是 | 是 | 元数据值 | +| resource | string | 是 | 是 | 元数据资源 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md b/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md index e769de72fd52adb1a42e5fd8be6b97ab2f8d139a..7bda59994ceff639fd483713fd499ed929bf20f9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -83,6 +83,6 @@ import wantConstant from '@ohos.ability.wantConstant' | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | 表示迁移是可拉回的。 | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | 如果未安装指定的功能,请安装该功能。 | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | 如果未安装,使用后台模式安装该功能。 | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | 指示清除其他任务的操作。可以为传递给**ohos.app.Context#startAbility**的**Want**设置此标志,并且必须与**flag_ABILITY_NEW_MISSION**一起使用。 | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | 指示清除其他任务的操作。可以为传递给 **[ohos.app.Context](js-apis-ability-context.md)** 中**startAbility**方法的**Want**设置此标志,并且必须与**flag_ABILITY_NEW_MISSION**一起使用。 | | FLAG_ABILITY_NEW_MISSION | 0x10000000 | 指示在历史任务堆栈上创建任务的操作。 | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | 指示如果启动能力的现有实例已位于任务堆栈的顶部,则将重用该实例。否则,将创建一个新的能力实例。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 60c07497fce954d417b4100e0b00d71c0dcb6016..d21009a4fd40f5f598d864edb1bcc7e14182c876 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -6,7 +6,8 @@ 该模块提供以下音频相关的常用功能: - [AudioManager](#audiomanager):音频管理。 -- [AudioRenderer](#audiorenderer8):音频播放,用于播放PCM(Pulse Code Modulation)音频数据。 +- [AudioRenderer](#audiorenderer8):音频渲染,用于播放PCM(Pulse Code Modulation)音频数据。 +- [AudioCapturer](#audiocapturer8):音频采集,用于录制PCM(Pulse Code Modulation)音频数据。 ## 导入模块 @@ -37,21 +38,73 @@ var audioManager = audio.getAudioManager(); createAudioRenderer(options: AudioRendererOptions): AudioRenderer -获取音频播放器。 +获取音频渲染器。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ---------------------------------------------- | ---- | ----------- | -| options | [AudioRendererOptions](#audiorendereroptions8) | 是 | 配置播放器. | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ---------------------------------------------- | ---- | ------------ | +| options | [AudioRendererOptions](#audiorendereroptions8) | 是 | 配置渲染器。 | **返回值**: | 类型 | 说明 | | -------------------------------- | ---------------- | -| [AudioRenderer](#audiorenderer8) | 音频播放器对象。 | +| [AudioRenderer](#audiorenderer8) | 音频渲染器对象。 | + +**示例:** + +``` +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} + +audio.createAudioRenderer(audioRendererOptions,(err, data) => { + if (err) { + console.error(`AudioRender Created : Error: ${err.message}`); + } + else { + console.info('AudioRender Created : Success : SUCCESS'); + audioRenderer = data; + } +}); +``` + +## audio.createAudioRenderer8+ + +createAudioRenderer(options: AudioRendererOptions): Promise + +获取音频渲染器。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------ | :--------------------------------------------- | :--- | :----------- | +| options | [AudioRendererOptions](#audiorendereroptions8) | 是 | 配置渲染器。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------- | ---------------- | +| Promise<[AudioRenderer](#audiorenderer8)> | 音频播放器对象。 | **示例:** @@ -77,6 +130,95 @@ var audioRendererOptions = { let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` +## audio.createAudioCapturer8+ + +createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback): void + +获取音频采集器。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------- | :--- | :--------------- | +| options | [AudioCapturerOptions](#AudioCapturerOptions) | 是 | 配置音频采集器。 | +| callback | AsyncCallback<[AudioCapturer](#AudioCapturer)> | 是 | 音频采集器对象。 | + +**示例:** + +``` +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 1 +} + +var audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo +} + +audio.createAudioCapturer(audioCapturerOptions,(err, data) => { + if (err) { + console.error(`AudioCapturer Created : Error: ${err.message}`); + } + else { + console.info('AudioCapturer Created : Success : SUCCESS'); + audioCapturer = data; + } +}); +``` + +## audio.createAudioCapturer8+ + +createAudioCapturer(options: AudioCapturerOptions): Promise + +获取音频采集器。使用promise 方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------ | :------------------- | :--- | :--------------- | +| options | AudioCapturerOptions | 是 | 配置音频采集器。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------- | -------------- | +| Promise<[AudioCapturer](#AudioCapturer8)> | 音频采集器对象 | + +**示例:** + +``` +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 1 +} + +var audioCapturerOptions = { + streamInfo: AudioStreamInfo, + capturerInfo: AudioCapturerInfo +} + +let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); +``` + ## AudioVolumeType 枚举,音频流类型。 @@ -122,17 +264,17 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device -| 名称 | 默认值 | 描述 | -| -------------- | ------ | --------------------------------------------------------- | -| INVALID | 0 | 无效设备。 | -| EARPIECE | 1 | 听筒。 | -| SPEAKER | 2 | 扬声器。 | -| WIRED_HEADSET | 3 | 有线耳机,带麦克风。 | -| WIRED_HEADPHONE| 4 | 有线耳机,无麦克风。 | -| BLUETOOTH_SCO | 7 | 蓝牙设备SCO(Synchronous Connection Oriented)连接。 | -| BLUETOOTH_A2DP | 8 | 蓝牙设备A2DP(Advanced Audio Distribution Profile)连接。 | -| MIC | 15 | 麦克风。 | -| USB_HEADSET | 22 | USB耳机,带麦克风。 | +| 名称 | 默认值 | 描述 | +| --------------- | ------ | --------------------------------------------------------- | +| INVALID | 0 | 无效设备。 | +| EARPIECE | 1 | 听筒。 | +| SPEAKER | 2 | 扬声器。 | +| WIRED_HEADSET | 3 | 有线耳机,带麦克风。 | +| WIRED_HEADPHONE | 4 | 有线耳机,无麦克风。 | +| BLUETOOTH_SCO | 7 | 蓝牙设备SCO(Synchronous Connection Oriented)连接。 | +| BLUETOOTH_A2DP | 8 | 蓝牙设备A2DP(Advanced Audio Distribution Profile)连接。 | +| MIC | 15 | 麦克风。 | +| USB_HEADSET | 22 | USB耳机,带麦克风。 | ## ActiveDeviceType @@ -213,22 +355,22 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | ENCODING_TYPE_INVALID | -1 | 无效。 | | ENCODING_TYPE_RAW | 0 | PCM编码。 | -## ContentType8+ +## ContentType 枚举,音频内容类型。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core -| 名称 | 默认值 | 描述 | -| ------------------------- | ------ | ---------- | -| CONTENT_TYPE_UNKNOWN | 0 | 未知类型。 | -| CONTENT_TYPE_SPEECH | 1 | 语音。 | -| CONTENT_TYPE_MUSIC | 2 | 音乐。 | -| CONTENT_TYPE_MOVIE | 3 | 电影。 | -| CONTENT_TYPE_SONIFICATION | 4 | 加密类型。 | -| CONTENT_TYPE_RINGTONE | 5 | 铃声。 | +| 名称 | 默认值 | 描述 | +| ---------------------------------- | ------ | ---------- | +| CONTENT_TYPE_UNKNOWN | 0 | 未知类型。 | +| CONTENT_TYPE_SPEECH | 1 | 语音。 | +| CONTENT_TYPE_MUSIC | 2 | 音乐。 | +| CONTENT_TYPE_MOVIE | 3 | 电影。 | +| CONTENT_TYPE_SONIFICATION | 4 | 加密类型。 | +| CONTENT_TYPE_RINGTONE8+ | 5 | 铃声。 | -## StreamUsage8+ +## StreamUsage 枚举,音频流使用类型。 @@ -239,7 +381,7 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | STREAM_USAGE_UNKNOWN | 0 | 未知类型。 | | STREAM_USAGE_MEDIA | 1 | 音频。 | | STREAM_USAGE_VOICE_COMMUNICATION | 2 | 语音通信。 | -| STREAM_USAGE_NOTIFICATION_RINGTONE | 3 | 通知铃声。 | +| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | 通知铃声。 | ## AudioState8+ @@ -259,7 +401,7 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ## AudioRendererRate8+ -枚举,播放速度。 +枚举,音频渲染速度。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer @@ -269,7 +411,7 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | RENDER_RATE_DOUBLE | 1 | 2倍速。 | | RENDER_RATE_HALF | 2 | 0.5倍数。 | -## InterruptType8+ +## InterruptType 枚举,中断类型。 @@ -280,7 +422,7 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | INTERRUPT_TYPE_BEGIN | 1 | 音频播放中断事件开始。 | | INTERRUPT_TYPE_END | 2 | 音频播放中断事件结束。 | -## InterruptForceType8+ +## InterruptForceType9+ 枚举,强制打断类型。 @@ -291,20 +433,20 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | INTERRUPT_FORCE | 0 | 由系统进行操作,强制打断音频播放。 | | INTERRUPT_SHARE | 1 | 由应用进行操作,可以选择打断或忽略。 | -## InterruptHint8+ +## InterruptHint 枚举,中断提示。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer -| 名称 | 默认值 | 描述 | -| --------------------- | ------ | -------------------------------------------- | -| INTERRUPT_HINT_NONE | 0 | 无提示。 | -| INTERRUPT_HINT_RESUME | 1 | 提示音频恢复。 | -| INTERRUPT_HINT_PAUSE | 2 | 提示音频暂停。 | -| INTERRUPT_HINT_STOP | 3 | 提示音频停止。 | -| INTERRUPT_HINT_DUCK | 4 | 提示音频躲避。(躲避:音量减弱,而不会停止) | -| INTERRUPT_HINT_UNDUCK | 5 | 提示音量恢复。 | +| 名称 | 默认值 | 描述 | +| ---------------------------------- | ------ | -------------------------------------------- | +| INTERRUPT_HINT_NONE8+ | 0 | 无提示。 | +| INTERRUPT_HINT_RESUME | 1 | 提示音频恢复。 | +| INTERRUPT_HINT_PAUSE | 2 | 提示音频暂停。 | +| INTERRUPT_HINT_STOP | 3 | 提示音频停止。 | +| INTERRUPT_HINT_DUCK | 4 | 提示音频躲避。(躲避:音量减弱,而不会停止) | +| INTERRUPT_HINT_UNDUCK8+ | 5 | 提示音量恢复。 | ## InterruptActionType @@ -334,28 +476,28 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ## AudioRendererInfo8+ -音频播放器信息。 +音频渲染器信息。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ---------------------------- | ---- | ---------------- | -| contentType | [ContentType](#contenttype8) | 是 | 媒体类型。 | -| usage | [StreamUsage](#streamusage8) | 是 | 音频流使用类型。 | -| rendererFlags | number | 是 | 音频播放器标志。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | --------------------------- | ---- | ---------------- | +| contentType | [ContentType](#contenttype) | 是 | 媒体类型。 | +| usage | [StreamUsage](#streamusage) | 是 | 音频流使用类型。 | +| rendererFlags | number | 是 | 音频渲染器标志。 | ## AudioRendererOptions8+ -音频播放器选项信息。 +音频渲染器选项信息。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer | 名称 | 类型 | 必填 | 说明 | | ------------ | ---------------------------------------- | ---- | ---------------- | | streamInfo | [AudioStreamInfo](#audiostreaminfo8) | 是 | 表示音频流信息。 | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 是 | 表示播放器信息。 | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 是 | 表示渲染器信息。 | -## InterruptEvent8+ +## InterruptEvent9+ 播放中断时,应用接收的中断事件。 @@ -363,9 +505,9 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | 名称 | 类型 | 必填 | 说明 | | --------- | ------------------------------------------ | ---- | ------------------------------------ | -| eventType | [InterruptType](#interrupttype8) | 是 | 中断事件类型,开始或是结束。 | -| forceType | [InterruptForceType](#interruptforcetype8) | 是 | 操作是由系统执行或是由应用程序执行。 | -| hintType | [InterruptHint](#interrupthint8) | 是 | 中断提示。 | +| eventType | [InterruptType](#interrupttype) | 是 | 中断事件类型,开始或是结束。 | +| forceType | [InterruptForceType](#interruptforcetype9) | 是 | 操作是由系统执行或是由应用程序执行。 | +| hintType | [InterruptHint](#interrupthint) | 是 | 中断提示。 | ## AudioInterrupt @@ -377,8 +519,8 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | 名称 | 类型 | 必填 | 说明 | | --------- | ------------------------------------------ | ---- | ------------------------------------ | -| streamUsage | [StreamUsage](#streamusage8) | 是 | 音频流使用类型。 | -| contentType | [ContentType](#contenttype8) | 是 | 音频打断媒体类型。 | +| streamUsage | [StreamUsage](#streamusage) | 是 | 音频流使用类型。 | +| contentType | [ContentType](#contenttype) | 是 | 音频打断媒体类型。 | | pauseWhenDucked | boolean | 是 | 音频打断时是否可以暂停音频播放(true表示音频播放可以在音频打断期间暂停,false表示相反)。 | ## InterruptAction @@ -392,14 +534,16 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | 名称 | 类型 | 必填 | 说明 | | --------- | ------------------------------------------ | ---- | ------------------------------------ | | actionType | [InterruptActionType](#interruptactiontype) | 是 | 事件返回类型。TYPE_ACTIVATED为焦点触发事件,TYPE_INTERRUPT为音频打断事件。 | -| type | [InterruptType](#interrupttype8) | 否 | 打断事件类型。 | -| hint | [InterruptHint](interrupthint8) | 否 | 打断事件提示。 | +| type | [InterruptType](#interrupttype) | 否 | 打断事件类型。 | +| hint | [InterruptHint](interrupthint) | 否 | 打断事件提示。 | | activated | boolean | 否 | 获得/释放焦点。true表示焦点获取/释放成功,false表示焦点获得/释放失败。 | ## VolumeEvent8+ 音量改变时,应用接收的事件。 +此接口为系统接口,三方应用不支持。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Volume | 名称 | 类型 | 必填 | 说明 | @@ -408,6 +552,65 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); | volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | | updateUi | boolean | 是 | 在UI中显示音量变化。 | +## DeviceChangeAction + +描述设备连接状态变化和设备信息。 + +**系统能力:**SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| :---------------- | :------------------------------------------------ | :--- | :----------------- | +| type | [DeviceChangeType](#DeviceChangeType) | 是 | 设备连接状态变化。 | +| deviceDescriptors | [AudioDeviceDescriptors](#AudioDeviceDescriptors) | 是 | 设备信息。 | + +## DeviceChangeType + +枚举,设备连接状态变化。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device + +| 名称 | 默认值 | 描述 | +| :--------- | :----- | :------------- | +| CONNECT | 0 | 设备连接。 | +| DISCONNECT | 1 | 断开设备连接。 | + +## AudioCapturerInfo8+ + +描述音频采集器信息。 + +**系统能力:** SystemCapability.Multimedia.Audio.Core + +| 名称 | 类型 | 必填 | 说明 | +| :------------ | :------------------------ | :--- | :--------------- | +| source | [SourceType](#sourcetype) | 是 | 音源类型。 | +| capturerFlags | number | 是 | 音频采集器标志。 | + +## SourceType8+ + +枚举,音源类型。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core + +| 名称 | 默认值 | 描述 | +| :------------------ | :----- | :------------- | +| SOURCE_TYPE_INVALID | -1 | 无效的音频源。 | +| SOURCE_TYPE_MIC | 0 | Mic音频源。 | + +## AudioScene8+ + +枚举,音频场景。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Communication + +| 名称 | 默认值 | 描述 | +| :------------------------------------------------- | :----- | :------------- | +| AUDIO_SCENE_DEFAULT | 0 | 默认音频场景。 | +| AUDIO_SCENE_RINGING(系统接口,三方应用不支持) | 1 | 响铃模式。 | +| AUDIO_SCENE_PHONE_CALL(系统接口,三方应用不支持) | 2 | 电话模式。 | +| AUDIO_SCENE_VOICE_CHAT | 3 | 语音聊天模式。 | + ## AudioManager 管理音频音量和音频设备。在调用AudioManager的接口前,需要先通过[getAudioManager](#audiogetaudiomanager)创建实例。 @@ -1325,12 +1528,14 @@ audioManager.isMicrophoneMute().then((value) => { }) ``` -### on('volumeChange') +### on('volumeChange')8+ on(type: 'volumeChange', callback: Callback\): void 监听系统音量变化事件。 +此接口为系统接口,三方应用不支持。 + **系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** @@ -1350,12 +1555,14 @@ audioManager.on('volumeChange', (volumeEvent) => { }) ``` -### on('ringerModeChange') +### on('ringerModeChange')8+ on(type: 'ringerModeChange', callback: Callback\): void 监听铃声模式变化事件。 +此接口为系统接口,三方应用不支持。 + **系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** @@ -1365,6 +1572,57 @@ on(type: 'ringerModeChange', callback: Callback\): void | type | string | 是 | 事件回调类型,支持的事件为:'ringerModeChange'(铃声模式变化事件,检测到铃声模式改变时,触发该事件)。 | | callback | Callback<[AudioRingMode](#audioringmode)> | 是 | 回调方法。 | +### on('deviceChange') + +on(type: 'deviceChange', callback: Callback): void + +设备更改。音频设备连接状态变化。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | 是 | 获取设备更新详情。 | + +**示例:** + +``` +audioManager.on('deviceChange', (deviceChanged) => { + console.info("device change type : " + deviceChanged.type); + console.info("device descriptor size : " + deviceChanged.deviceDescriptors.length); + console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceRole); + console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceType); +}); +``` + +### off('deviceChange') + +off(type: 'deviceChange', callback?: Callback): void + +取消订阅音频设备连接变化事件。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | 否 | 获取设备更新详情。 | + +**示例:** + +``` +audioManager.off('deviceChange', (deviceChanged) => { + console.log("Should be no callback."); +}); +``` + ### on('interrupt') on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void @@ -1437,6 +1695,118 @@ this.audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { }); ``` +### setAudioScene8+ + +setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void + +设置音频场景模式,使用callback方式异步返回结果。 + +此接口为系统接口,三方应用不支持。 + +**系统能力:** SystemCapability.Multimedia.Audio.Communication + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------------------- | :--- | :------------------- | +| scene | AudioScene | 是 | 音频场景模式。 | +| callback | AsyncCallback | 是 | 用于返回结果的回调。 | + +**示例:** + +``` +audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { + if (err) { + console.error('Failed to set the audio scene mode.​ ${err.message}'); + return; + } + console.log('Callback invoked to indicate a successful setting of the audio scene mode.'); +}); +``` + +### setAudioScene8+ + +setAudioScene\(scene: AudioScene\): Promise + +设置音频场景模式,使用Promise方式返回异步结果。 + +此接口为系统接口,三方应用不支持。 + +**系统能力:**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----------------------------------- | :--- | :------------- | +| scene | AudioScene | 是 | 音频场景模式。 | + +**返回值:** + +| 类型 | 说明 | +| :------------- | :------------------- | +| Promise | 用于返回结果的回调。 | + +**示例:** + +``` +audioManager.setAudioScene(audio.AudioSceneMode.AUDIO_SCENE_PHONE_CALL).then(() => { + console.log('Promise returned to indicate a successful setting of the audio scene mode.'); +}).catch ((err) => { + console.log('Failed to set the audio scene mode'); +}); +``` + +### getAudioScene8+ + +getAudioScene\(callback: AsyncCallback\): void + +获取音频场景模式,使用callback方式返回异步结果。 + +**系统能力:**SystemCapability.Multimedia.Audio.Communication + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :-------------------------------------------------- | :--- | :--------------------------- | +| callback | AsyncCallback<AudioScene> | 是 | 用于返回音频场景模式的回调。 | + +**示例:** + +``` +audioManager.getAudioScene((err, value) => { + if (err) { + console.error('Failed to obtain the audio scene mode.​ ${err.message}'); + return; + } + console.log('Callback invoked to indicate that the audio scene mode is obtained.' + value); +}); +``` + + +### getAudioScene8+ + +getAudioScene\(\): Promise + +获取音频场景模式,使用Promise方式返回异步结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Communication + +**返回值:** + +| 类型 | 说明 | +| :-------------------------------------------- | :--------------------------- | +| Promise<AudioScene> | 用于返回音频场景模式的回调。 | + +**示例:** + +``` +audioManager.getAudioScene().then((value) => { + console.log('Promise returned to indicate that the audio scene mode is obtained.' + value); +}).catch ((err) => { + console.log('Failed to obtain the audio scene mode'); +}); +``` + ## AudioDeviceDescriptor 描述音频设备。 @@ -1486,13 +1856,21 @@ promise.then(async function (audioDeviceDescriptors) { ## AudioRenderer8+ -提供音频播放的相关接口。在调用AudioRenderer的接口前,需要先通过[createAudioRenderer](#audiocreateaudiorenderer8)创建实例。 +提供音频渲染的相关接口。在调用AudioRenderer的接口前,需要先通过[createAudioRenderer](#audiocreateaudiorenderer8)创建实例。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +### state8+ + +只读 state: AudioState + +定义当前渲染器的状态。 -### 属性 +**参数:** -| 名称 | 类型 | 可读 | 可写 | 说明 | +| 名称 | 参数型 | 可读 | 可写 | 说明 | | ----- | -------------------------- | ---- | ---- | ------------------ | -| state | [AudioState](#audiostate8) | 是 | 否 | 当前播放器的状态。 | +| state | [AudioState](#audiostate8) | 是 | 否 | 音频渲染器的状态。 | **示例:** @@ -1504,15 +1882,15 @@ var state = audioRenderer.state; getRendererInfo(callback: AsyncCallback): void -获取当前被创建的音频播放器的信息,使用callback方式异步返回结果。 +获取当前被创建的音频渲染器的信息,使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------------------------------------------- | :--- | :------------------------- | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | 是 | 回调返回音频播放器的信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------------------------------------------- | :--- | :--------------------- | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | 是 | 返回音频渲染器的信息。 | **示例:** @@ -1529,7 +1907,7 @@ audioRenderer.getRendererInfo((err, rendererInfo)=>{ getRendererInfo(): Promise -获取当前被创建的音频播放器的信息,使用Promise方式异步返回结果。 +获取当前被创建的音频渲染器的信息,使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1537,7 +1915,7 @@ getRendererInfo(): Promise | 类型 | 说明 | | -------------------------------------------------- | ------------------------------- | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise用于返回音频播放器信息。 | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise用于返回音频渲染器信息。 | **示例:** @@ -1545,9 +1923,9 @@ getRendererInfo(): Promise let streamInfo = await audioRenderer.getStreamInfo(); console.log('Renderer GetStreamInfo:'); console.log('Renderer sampling rate:' + streamInfo.samplingRate); -console.log('Renderer channel:' + streamInfo.AudioChannel); -console.log('Renderer format:' + streamInfo.AudioSampleFormat); -console.log('Renderer encoding type:' + streamInfo.AudioEncodingType); +console.log('Renderer channel:' + streamInfo.channels); +console.log('Renderer format:' + streamInfo.sampleFormat); +console.log('Renderer encoding type:' + streamInfo.encodingType); ``` ### getStreamInfo8+ @@ -1570,9 +1948,9 @@ getStreamInfo(callback: AsyncCallback): void audioRenderer.getStreamInfo((err, streamInfo)=>{ console.log('Renderer GetStreamInfo:'); console.log('Renderer sampling rate:' + streamInfo.samplingRate); - console.log('Renderer channel:' + streamInfo.AudioChannel); - console.log('Renderer format:' + streamInfo.AudioSampleFormat); - console.log('Renderer encoding type:' + streamInfo.AudioEncodingType); + console.log('Renderer channel:' + streamInfo.channels); + console.log('Renderer format:' + streamInfo.sampleFormat); + console.log('Renderer encoding type:' + streamInfo.encodingType); }) ``` @@ -1605,7 +1983,7 @@ console.log('Renderer encoding type:' + streamInfo.AudioEncodingType); start(callback: AsyncCallback): void -启动音频播放器。使用callback方式异步返回结果。 +启动音频渲染器。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1631,7 +2009,7 @@ audioRenderer.start((err)=>{ start(): Promise -启动音频播放器。使用Promise方式异步返回结果。 +启动音频渲染器。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1651,7 +2029,7 @@ await audioRenderer.start(); pause(callback: AsyncCallback\): void -暂停音频播放器。使用callback方式异步返回结果。 +暂停渲染。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1677,7 +2055,7 @@ audioRenderer.pause((err)=>{ pause(): Promise\ -暂停音频播放器。使用Promise方式异步返回结果。 +暂停渲染。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1697,7 +2075,7 @@ await audioRenderer.pause(); drain(callback: AsyncCallback\): void -检查播放缓冲区是否已被耗尽。使用callback方式异步返回结果。 +检查缓冲区是否已被耗尽。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1723,7 +2101,7 @@ audioRenderer.drain((err)=>{ drain(): Promise\ -检查播放缓冲区是否已被耗尽。使用Promise方式异步返回结果。 +检查缓冲区是否已被耗尽。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1743,7 +2121,7 @@ await audioRenderer.drain(); stop(callback: AsyncCallback\): void -停止播放。使用callback方式异步返回结果。 +停止渲染。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1769,7 +2147,7 @@ audioRenderer.stop((err)=>{ stop(): Promise\ -停止播放。使用Promise方式异步返回结果。 +停止渲染。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1789,7 +2167,7 @@ await audioRenderer.stop(); release(callback: AsyncCallback\): void -释放音频播放器。使用callback方式异步返回结果。 +释放音频渲染器。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1893,7 +2271,7 @@ if (writtenbytes < 0) { getAudioTime(callback: AsyncCallback\): void -获取时间戳。使用callback方式异步返回结果。 +获取时间戳(从 1970 年 1 月 1 日开始)。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1915,7 +2293,7 @@ audioRenderer.getAudioTime((err, timestamp)=>{ getAudioTime(): Promise\ -获取时间戳。使用Promise方式异步返回结果。 +获取时间戳(从 1970 年 1 月 1 日开始)。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1936,7 +2314,7 @@ console.log('Current timestamp: ' + timestamp); getBufferSize(callback: AsyncCallback\): void -获取音频播放器的最小缓冲区大小。使用callback方式异步返回结果。 +获取音频渲染器的最小缓冲区大小。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1962,7 +2340,7 @@ ss.readSync(buf); getBufferSize(): Promise\ -获取音频播放器的最小缓冲区大小。使用Promise方式异步返回结果。 +获取音频渲染器的最小缓冲区大小。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1984,7 +2362,7 @@ ss.readSync(buf); setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void -设置音频播放速率。使用callback方式异步返回结果。 +设置音频渲染速率。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -1992,7 +2370,7 @@ setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 播放的速率。 | +| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 渲染的速率。 | | callback | AsyncCallback\ | 是 | 用于返回执行结果的回调。 | **示例:** @@ -2011,7 +2389,7 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err)=> setRenderRate(rate: AudioRendererRate): Promise\ -设置音频播放速率。使用Promise方式异步返回结果。 +设置音频渲染速率。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -2019,7 +2397,7 @@ setRenderRate(rate: AudioRendererRate): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ---------------------------------------- | ---- | ------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 播放的速率。 | +| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 渲染的速率。 | **返回值:** @@ -2037,7 +2415,7 @@ await audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL); getRenderRate(callback: AsyncCallback\): void -获取当前播放速率。使用callback方式异步返回结果。 +获取当前渲染速率。使用callback方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -2045,7 +2423,7 @@ getRenderRate(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | 是 | 回调返回播放速率。 | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | 是 | 回调返回渲染速率。 | **示例:** @@ -2059,7 +2437,7 @@ audioRenderer.getRenderRate((err, renderrate)=>{ getRenderRate(): Promise\ -获取当前播放速率。使用Promise方式异步返回结果。 +获取当前渲染速率。使用Promise方式异步返回结果。 **系统能力**: SystemCapability.Multimedia.Audio.Renderer @@ -2067,7 +2445,7 @@ getRenderRate(): Promise\ | 类型 | 说明 | | ------------------------------------------------- | ------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise回调返回播放速率。 | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise回调返回渲染速率。 | **示例:** @@ -2076,7 +2454,7 @@ let renderRate = await audioRenderer.getRenderRate(); console.log('getRenderRate: ' + renderrate); ``` -### on('interrupt')8+ +### on('interrupt')9+ on(type: 'interrupt', callback: Callback\): void @@ -2089,7 +2467,7 @@ on(type: 'interrupt', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 事件回调类型,支持的事件为:'interrupt'(中断事件被触发,音频播放被中断。) | -| callback | Callback<[InterruptEvent](#interruptevent8)> | 是 | 被监听的中断事件的回调。 | +| callback | Callback<[InterruptEvent](#interruptevent9)> | 是 | 被监听的中断事件的回调。 | **示例:** @@ -2121,5 +2499,693 @@ audioRenderer.on('interrupt', (interruptEvent) => { }) ``` +### on('markReach')8+ + +on(type: 'markReach', frame: number, callback: (position: number) => {}): void + +订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被调用。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :---------------------------------------- | +| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | +| callback | (position: number) => {} | 是 | 触发事件时调用的回调。 | + +**示例:** + +``` +audioRenderer.on('markReach', 1000, (position) => { + if (position == "1000") { + console.log('ON Triggered successfully'); + } +}); +``` + + +### off('markReach') 8+ + +off(type: 'markReach'): void + +取消订阅标记事件。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :------------------------------------------------ | +| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'markReach'。 | + +**示例:** + +``` +audioRenderer.off('markReach'); +``` + +### on('periodReach') 8+ +on(type: "periodReach", frame: number, callback: (position: number) => {}): void +订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被循环调用。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'periodReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | +| callback | (position: number) => {} | 是 | 触发事件时调用的回调。 | + +**示例:** + +``` +audioRenderer.on('periodReach', 1000, (position) => { + if (position == "1000") { + console.log('ON Triggered successfully'); + } +}); +``` + +### off('periodReach') 8+ + +off(type: 'periodReach'): void + +取消订阅标记事件。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :-------------------------------------------------- | +| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'periodReach'。 | + +**示例:** + +``` +audioRenderer.off('periodReach') +``` + +### on('stateChange') 8+ + +on(type: 'stateChange', callback: Callback): void + +订阅监听状态变化。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'stateChange'。 | +| callback | [AudioState](#AudioState8) | 是 | 返回监听的状态。 | + +**示例:** + +``` +audioRenderer.on('stateChange', (state) => { + if (state == 1) { + console.log("audio renderer state is: STATE_PREPARED"); + } + if (state == 2) { + console.log("audio renderer state is: STATE_RUNNING"); + } +}); +``` + +## AudioCapturer8+ + +提供音频采集的相关接口。在调用AudioCapturer的接口前,需要先通过[createAudioCapturer](#audiocreateaudiocapturer8)创建实例。 + +### state8+ + +只读 state: AudioState + +定义当前采集器状态。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +| 名称 | 参数型 | 可读 | 可写 | 说明 | +| :---- | :------------------------- | :--- | :--- | :--------------- | +| state | [AudioState](#audiostate8) | Yes | No | 音频采集器状态。 | + +**示例:** + +``` +var state = audioCapturer.state; +``` + +### getCapturerInfo8+ + +getCapturerInfo(callback: AsyncCallback): void + +获取采集器信息。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :-------------------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回采集器信息。 | + +**示例:** + +``` +audioCapturer.getCapturerInfo((err, capturerInfo)=>{ + if (err) { + console.error('Failed to get capture info'); + } else { + console.log('Capturer getCapturerInfo:'); + console.log('Capturer source:' + capturerInfo.source); + console.log('Capturer flags:' + capturerInfo.capturerFlags); + } +}); +``` + + +### getCapturerInfo8+ + +getCapturerInfo(): Promise + +获取采集器信息。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**返回值:** + +| 类型 | 说明 | +| :------------------------------------------------ | :---------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | 使用Promise方式异步返回采集器信息。 | + +**示例:** + +``` +audioCapturer.getCapturerInfo().then((capturerInfo) => { + console.log('Capturer getCapturerInfo:'); + console.log('Capturer source:' + capturerInfo.source); + console.log('Capturer flags:' + capturerInfo.capturerFlags); +}).catch ((err) => { + console.log("Failed to get capturer info"); +}); +``` + +### getStreamInfo8+ + +getStreamInfo(callback: AsyncCallback): void + +获取采集器流信息。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :-------------------------------------------------------- | :--- | :------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#AudioRendererOptions8)\> | 是 | 使用callback方式异步返回流信息。 | + +**示例:** + +``` +audioCapturer.start((err)=>{ + if (err) { + console.error('Failed to get stream info'); + } else { + console.log('Capturer GetStreamInfo:'); + console.log('Capturer sampling rate:' + streamInfo.samplingRate); + console.log('Capturer channel:' + streamInfo.channels); + console.log('Capturer format:' + streamInfo.sampleFormat); + console.log('Capturer encoding type:' + streamInfo.encodingType); + } +}); +``` + +### getStreamInfo8+ + +getStreamInfo(): Promise + +获取采集器流信息。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**返回值:** + +| 类型 | 说明 | +| :-------------------------------------------------- | :------------------------------ | +| Promise<[AudioStreamInfo](#AudioRendererOptions8)\> | 使用Promise方式异步返回流信息。 | + +**示例:** + +``` +audioCapturer.getStreamInfo().then((streamInfo) => { + console.log('Capturer GetStreamInfo:'); + console.log('Capturer sampling rate:' + streamInfo.samplingRate); + console.log('Capturer channel:' + streamInfo.channels); + console.log('Capturer format:' + streamInfo.sampleFormat); + console.log('Capturer encoding type:' + streamInfo.encodingType); +}).catch ((err) => { + console.log("Failed to get stream info"); +}); +``` + +### start8+ + +start(callback: AsyncCallback): void + +启动音频采集器。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | + +**示例:** + +``` +audioCapturer.start((err)=>{ + if (err) { + console.error('Capturer start failed.'); + } else { + console.info('Capturer start success.'); + } +}); +``` + + +### start8+ + +start(): Promise + +启动音频采集器。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**返回值:** + +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | + +**示例:** + +``` +audioCapturer.start().then(() => { + console.log("capturer start success"); +}).catch ((err) => { + console.log("Failed to start capturer"); +}); +``` + +### stop8+ + +stop(callback: AsyncCallback): void + +停止采集。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | + +**示例:** + +``` +audioCapturer.stop((err)=>{ + if (err) { + console.error('Capturer stop failed'); + } else { + console.log('Capturer stopped.'); + } +}); +``` + + +### stop8+ + +stop(): Promise + +停止采集。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**返回值:** + +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | + +**示例:** + +``` +audioCapturer.stop().then(() => { + console.log("capturer stop success"); +}).catch ((err) => { + console.log("Failed to stop capturer"); +}); +``` + +### release8+ + +release(callback: AsyncCallback): void + +释放采集器。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :---------------------------------- | +| callback | AsyncCallback | 是 | Callback used to return the result. | + +**示例:** + +``` +audioCapturer.release((err)=>{ + if (err) { + console.error('capturer release failed'); + } else { + console.log('capturer released.'); + } +}); +``` + + +### release8+ + +release(): Promise + +释放采集器。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**返回值:** + +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | + +**示例:** + +``` +audioCapturer.release().then(() => { + console.log("capturer release success"); +}).catch ((err) => { + console.log("Failed to release capturer"); +}); +``` + + +### read8+ + +read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void + +读入缓冲区。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数** + +| 参数名 | 类型 | 必填 | 说明 | +| :------------- | :-------------------------- | :--- | :------------------------------- | +| size | number | 是 | 读入的字节数。 | +| isBlockingRead | boolean | 是 | 是否阻塞读操作。 | +| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区。 | + +**示例:** + +``` +audioCapturer.read(bufferSize, true, async(err, buffer) => { + if (!err) { + console.log("Success in reading the buffer data"); + var number = fileio.writeSync(fd, buffer); + } +}; +``` + + +### read8+ + +read(size: number, isBlockingRead: boolean): Promise + +读入缓冲区。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------------- | :------ | :--- | :--------------- | +| size | number | 是 | 读入的字节数。 | +| isBlockingRead | boolean | 是 | 是否阻塞读操作。 | + +**返回值:** + +| 类型 | 说明 | +| :-------------------- | :----------------------------------------------------- | +| Promise | 如果操作成功,返回读取的缓冲区数据;否则返回错误代码。 | + +**示例:** + +``` +audioCapturer.read(size, true).then((buffer) => { + console.log("Success in reading the buffer data"); + var number = fileio.writeSync(fd, buffer); +}).catch ((err) => { + console.log("Failed to read data!"); +}); +``` + + +### getAudioTime8+ + +getAudioTime(callback: AsyncCallback): void + +获取时间戳(从1970年1月1日开始),单位为纳秒。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | + +**示例:** + +``` +audioCapturer.getAudioTime((err, timestamp)=>{ + console.log('Current timestamp: ' + timestamp); +}); +``` + + +### getAudioTime8+ + +getAudioTime(): Promise + +获取时间戳(从1970年1月1日开始),单位为纳秒。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**返回值:** + +| 类型 | 说明 | +| :--------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | + +**示例:** + +``` +audioCapturer.getAudioTime().then((audioTime) => { + console.log("Success in getting the audio time"); +}).catch ((err) => { + console.log("Failed to get the audio time"); +}); +``` + + +### getBufferSize8+ + +getBufferSize(callback: AsyncCallback): void + +获取采集器合理的最小缓冲区大小。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区大小。 | + +**示例:** + +``` +audioCapturer.getBufferSize((err, bufferSize)=>{ + if (!err) { + console.log('BufferSize : ' + bufferSize); + var buffer = await audioCapturer.read(bufferSize, true); + } +}); +``` + + +### getBufferSize8+ + +getBufferSize(): Promise + +获取采集器合理的最小缓冲区大小。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**返回值:** + +| 类型 | 说明 | +| :--------------- | :---------------------------------- | +| Promise | 使用Promise方式异步返回缓冲区大小。 | + +**示例:** + +``` +audioCapturer.getBufferSize().then((bufferSize) => { + console.log("Success in getting the buffer size"); + var buffer = await audioCapturer.read(bufferSize, true); +}).catch ((err) => { + console.log("Failed to get the buffer size"); +}); +``` + + +### on('markReach')8+ + +on(type: 'markReach', frame: number, callback: (position: number) => {}): void + +订阅标记到达的事件。 当采集的帧数达到 frame 参数的值时,回调被触发。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :---------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于0。 | +| callback | position: number) => {} | 是 | 使用callback方式异步返回被触发事件的回调。 | + +**示例:** + +``` +audioCapturer.on('markReach', 1000, (position) => { + if (position == "1000") { + console.log('ON Triggered successfully'); + } +}); +``` + +### off('markReach')8+ + +off(type: 'markReach'): void + +取消订阅标记到达的事件。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :-------------------------------------------- | +| type | string | 是 | 取消事件回调类型,支持的事件为:'markReach'。 | + +**示例:** + +``` +audioCapturer.off('markReach'); +``` + +### on('periodReach')8+ + +on(type: "periodReach", frame: number, callback: (position: number) => {}): void + +订阅到达标记的事件。 当采集的帧数达到 frame 参数的值时,回调被循环调用。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'periodReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于0。 | +| callback | (position: number) => {} | 是 | 使用callback方式异步返回被触发事件的回调 | + +**示例:** + +``` +audioCapturer.on('periodReach', 1000, (position) => { + if (position == "1000") { + console.log('ON Triggered successfully'); + } +}); +``` + +### off('periodReach')8+ + +off(type: 'periodReach'): void + +取消订阅标记到达的事件。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :---------------------------------------------- | +| type | string | Yes | 取消事件回调类型,支持的事件为:'periodReach'。 | + +**示例:** + +``` +audioCapturer.off('periodReach') +``` + +### on('stateChange') 8+ + +on(type: 'stateChange', callback: Callback): void + +订阅监听状态变化。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'stateChange'。 | +| callback | [AudioState](#AudioState8) | 是 | 返回监听的状态。 | + +**示例:** + +``` +audioCapturer.on('stateChange', (state) => { + if (state == 1) { + console.log("audio capturer state is: STATE_PREPARED"); + } + if (state == 2) { + console.log("audio capturer state is: STATE_RUNNING"); + } +}); +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-camera.md b/zh-cn/application-dev/reference/apis/js-apis-camera.md index 66bf11d3301b3f0c1e7896b3c032a1fd399cd239..ab8cf746f11690dfc0982bf8905c9ee12e2e38d5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -23,10 +23,10 @@ getCameraManager(context: Context, callback: AsyncCallback): voi **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|-------------------------------|-----------|-----------------------------------------------------| -| context | Context | 是 | 应用上下文。 | -| callback | AsyncCallback<[CameraManager](#cameramanager)\> | 是 | 回调函数,用于获取相机管理器实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | ---------------------------------- | +| context | Context | 是 | 应用上下文。 | +| callback | AsyncCallback<[CameraManager](#cameramanager)\> | 是 | 回调函数,用于获取相机管理器实例。 | **示例:** @@ -50,15 +50,15 @@ getCameraManager(context: Context): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------| -| context | Context | 是 | 应用上下文。 | +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------ | +| context | Context | 是 | 应用上下文。 | **返回值:** -| 类型 | 说明 | -|-------------------------|--------------------------------------------------------| -| Promise<[CameraManager](#cameramanager)\> | 使用Promise的方式获取一个相机管理器实例。 | +| 类型 | 说明 | +| ----------------------------------------- | ----------------------------------------- | +| Promise<[CameraManager](#cameramanager)\> | 使用Promise的方式获取一个相机管理器实例。 | **示例:** @@ -72,58 +72,54 @@ camera.getCameraManager(context).then((cameraManger) => { 枚举,相机状态。 -| 名称 | 默认值 | 说明 | -|---------------------------|---------------|--------------------| -| CAMERA_STATUS_APPEAR | 0 | 相机存在。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_STATUS_DISAPPEAR | 1 | 相机不存在。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_STATUS_AVAILABLE | 2 | 相机就绪。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_STATUS_UNAVAILABLE | 3 | 相机未就绪。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| ------------------------- | ------ | ------------ | +| CAMERA_STATUS_APPEAR | 0 | 相机存在。 | +| CAMERA_STATUS_DISAPPEAR | 1 | 相机不存在。 | +| CAMERA_STATUS_AVAILABLE | 2 | 相机就绪。 | +| CAMERA_STATUS_UNAVAILABLE | 3 | 相机未就绪。 | ## CameraPosition 枚举,相机方向。 -| 名称 | 默认值 | 说明 | -|-----------------------------|---------------|-----------------------| -| CAMERA_POSITION_UNSPECIFIED | 0 | 未指定方向相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_POSITION_BACK | 1 | 后置相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_POSITION_FRONT | 2 | 前置相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| --------------------------- | ------ | ---------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | 未指定方向相机。 | +| CAMERA_POSITION_BACK | 1 | 后置相机。 | +| CAMERA_POSITION_FRONT | 2 | 前置相机。 | ## CameraType 枚举,相机类型。 -| 名称 | 默认值 | 说明 | -|-------------------------|---------------|-------------------------| -| CAMERA_TYPE_UNSPECIFIED | 0 | 未指定相机类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_TYPE_ULTRA_WIDE | 2 | 超级广角相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_TYPE_TRUE_DEPTH | 4 | 深度相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| ----------------------- | ------ | ---------------- | +| CAMERA_TYPE_UNSPECIFIED | 0 | 未指定相机类型。 | +| CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。 | +| CAMERA_TYPE_ULTRA_WIDE | 2 | 超级广角相机。 | +| CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。 | +| CAMERA_TYPE_TRUE_DEPTH | 4 | 深度相机。 | ## ConnectionType 枚举,相机连接类型。 -| 名称 | 默认值 | 说明 | -|------------------------------|---------------|----------------------------| -| CAMERA_CONNECTION_BUILT_IN | 0 | 内置相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_CONNECTION_USB_PLUGIN | 1 | 外置USB相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_CONNECTION_REMOTE | 2 | 分布式相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core | - +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 -## CameraFormat - -枚举,照片格式。 - -| 名称 | 默认值 | 说明 | -|----------------------------|---------------|---------------------| -| CAMERA_FORMAT_YCRCb_420_SP | 1003 | YCRCb格式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_FORMAT_JPEG | 2000 | JPEG格式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_FORMAT_AVC | 3000 | AVC格式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| CAMERA_FORMAT_HEVC | 3001 | HEVC格式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +| 名称 | 默认值 | 说明 | +| ---------------------------- | ------ | ------------- | +| CAMERA_CONNECTION_BUILT_IN | 0 | 内置相机。 | +| CAMERA_CONNECTION_USB_PLUGIN | 1 | 外置USB相机。 | +| CAMERA_CONNECTION_REMOTE | 2 | 分布式相机。 | ## CameraManager @@ -140,9 +136,9 @@ getCameras(callback: AsyncCallback\>): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|--------------------------------|-----------|---------------------------------------------------------| -| callback | AsyncCallback\> | 是 | 使用callback方式获取支持的相机列表。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback\> | 是 | 使用callback方式获取支持的相机列表。 | **示例:** @@ -166,9 +162,9 @@ getCameras(): Promise\> **返回值:** -| 类型 | 说明 | -|------------------------|--------------------------------------------------------| -| Promise\> | 使用promise获取支持相机列表。 | +| 类型 | 说明 | +| ----------------------------------- | ----------------------------- | +| Promise\> | 使用promise获取支持相机列表。 | **示例:** @@ -189,10 +185,10 @@ createCameraInput(cameraId: string, callback: AsyncCallback): void **参数:** -| 名称 | 默认值 | 必填 | 说明 | -|----------|------------------------------|-----------|--------------------------------------------------| -| cameraId | string | 是 | 指定相机ID。 | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | +| 名称 | 默认值 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| cameraId | string | 是 | 指定相机ID。 | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | **示例:** @@ -216,15 +212,15 @@ createCameraInput(cameraId: string): Promise **参数:** -| 名称 | 默认值 | 必填 | 说明 | -|----------|-----------------------------|-----------|------------------------------------------| -| cameraId | string | 是 | 指定相机ID。 | +| 名称 | 默认值 | 必填 | 说明 | +| -------- | ------ | ---- | ------------ | +| cameraId | string | 是 | 指定相机ID。 | **返回值:** -| 类型 | 说明 | -|-------------------------|-------------------------------------------------| -| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | +| 类型 | 说明 | +| ------------------------------------- | ---------------------------------------- | +| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | **示例:** @@ -244,10 +240,10 @@ createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCal **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------------|----------------------------|-----------|---------------------------------------------------| -| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。 | -| cameraType | [CameraType](#cameratype) | 是 | 相机类型。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------- | ------------------------------------------- | ---- | ----------------------------------- | +| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| cameraType | [CameraType](#cameratype) | 是 | 相机类型。 | | callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | **示例:** @@ -272,15 +268,15 @@ createCameraInput(position: CameraPosition, type: CameraType): Promise | 使用Promise的方式获取CameraInput的实例。 | **示例:** @@ -301,10 +297,10 @@ on(type: 'cameraStatus', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :--------------------------------------------------- | -| type | string | 是 | 监听事件。 | -| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取相机状态变化信息。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :---------------------------------------------------- | :--- | :----------------------------------- | +| type | string | 是 | 监听事件。 | +| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取相机状态变化信息。 | **示例:** @@ -319,12 +315,14 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => { 相机实例。 -| 名称 | 类型 | 只读 | 说明 | -|----------------|----------------|----------|------------------------| -| cameraId | string | 是 | 相机ID。
**系统能力:** SystemCapability.Multimedia.Camera.Core| -| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| cameraType | [CameraType](#cameratype) | 是 | 相机类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| connectionType | [ConnectionType](#connectiontype) | 是 | 相机连接类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 类型 | 只读 | 说明 | +| -------------- | --------------------------------- | ---- | -------------- | +| cameraId | string | 是 | 相机ID。 | +| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| cameraType | [CameraType](#cameratype) | 是 | 相机类型。 | +| connectionType | [ConnectionType](#connectiontype) | 是 | 相机连接类型。 | **示例:** @@ -343,10 +341,12 @@ var cameraId = cameraObj.connectionType; 相机状态信息。 -| 名称 | 类型 | 说明 | -|----------------|----------------|------------------| -| camera | [Camera](#camera) | 相机信息。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| status | [CameraStatus](#camerastatus) | 相机状态。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 类型 | 说明 | +| ------ | ----------------------------- | ---------- | +| camera | [Camera](#camera) | 相机信息。 | +| status | [CameraStatus](#camerastatus) | 相机状态。 | ## CameraInput @@ -363,9 +363,9 @@ getCameraId(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|------------------------|-----------|---------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取相机ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取相机ID。 | **示例:** @@ -389,9 +389,9 @@ getCameraId(): Promise **返回值:** -| 类型 | 说明 | -|------------------------|--------------------------------------| -| Promise | 使用Promise的方式获取相机ID。 | +| 类型 | 说明 | +| ---------------- | ----------------------------- | +| Promise | 使用Promise的方式获取相机ID。 | **示例:** @@ -401,204 +401,6 @@ cameraInput.getCameraId().then((cameraId) => { }) ``` -### getSupportedSizes - -getSupportedSizes\(format: CameraFormat, callback: AsyncCallback\>\): void - -根据指定格式,获取相机支持的分辨率,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -|----------|------------------------------|-----------|---------------------------------------------| -| format | [CameraFormat](#cameraformat) | 是 | 指定照片格式。 | -| callback | AsyncCallback\> | 是 | 回调函数,用于获取相机支持分辨率。 | - -**示例:** - -``` -cameraInput.getSupportedSizes(format, (err, sizes) => { - if (err) { - console.error('Failed to get the supported sizes. ${err.message}'); - return; - } - console.log('Callback returned with the supported sizes:' + sizes); -}) -``` - -### getSupportedSizes - -getSupportedSizes\(format: CameraFormat\): Promise\> - -根据指定格式,获取相机支持的分辨率,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------ | ----------------------------- | ---- | -------------- | -| format | [CameraFormat](#cameraformat) | 是 | 指定照片格式。 | - -**返回值:** - -| 类型 | 说明 | -|------------------------|---------------------------------------------| -| Promise\> | 使用Promise的方式获取相机支持的分辨率。 | - -**示例:** - -``` -cameraInput.getSupportedSizes(format).then((sizes) => { - console.log('Promise returned with supported sizes: ' + sizes); -}) -``` - -### getSupportedPreviewFormats - -getSupportedPreviewFormats\(callback: AsyncCallback\>\): void - -获取相机预览图片的支持格式,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\> | 是 | 回调函数,用于获取预览图片的支持格式。 | - -**示例:** - -``` -cameraInput.getSupportedPreviewFormats((err, previewFormats) => { - if (err) { - console.error('Failed to get the supported preview formats. ${err.message}'); - return; - } - console.log('Callback returned with supported preview formats: ' + previewFormats.length); -}) -``` - -### getSupportedPreviewFormats - -getSupportedPreviewFormats\(\): Promise\> - -获取相机预览图片的支持格式,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -|--------------------------------|-------------------------------------------------------| -| Promise\> | 使用Promise的方式获取预览图片的支持格式。 | - -**示例:** - -``` -cameraInput.getSupportedPreviewFormats().then((previewFormats) => { - console.log('Promise returned with supported preview formats.' + previewFormats.length); -}) -``` - -### getSupportedPhotoFormats - -getSupportedPhotoFormats\(callback: AsyncCallback\>\): void - -获取照片的支持格式,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -|----------|--------------------------------------|-----------|-------------------------------------------------| -| callback | AsyncCallback\> | 是 | 回调函数,用于获取支持的照片格式。 | - -**示例:** - -``` -cameraInput.getSupportedPhotoFormats((err, photoFormats) => { - if (err) { - console.error('Failed to get the supported photo formats. ${err.message}'); - return; - } - console.log('Callback returned with supported photo formats'); -}) -``` - -### getSupportedPhotoFormats - -getSupportedPhotoFormats\(\): Promise\> - -获取照片的支持格式,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -|--------------------------------|---------------------------------------------------| -| Promise\> | 使用Promise的方式获取支持的照片格式。 | - -**示例:** - -``` -cameraInput.getSupportedPhotoFormats().then((photoFormats) => { - console.log('Promise returned with supported photo formats.' + photoFormats.length); -}) -``` - -### getSupportedVideoFormats - -getSupportedVideoFormats\(callback: AsyncCallback\>\): void - -获取录制视频的支持格式,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -|----------|--------------------------------------|-----------|-------------------------------------------------| -| callback | AsyncCallback\> | 是 | 回调函数,用于获取支持的视频格式。 | - -**示例:** - -``` -cameraInput.getSupportedVideoFormats((err, videoFormats) => { - if (err) { - console.error('Failed to get the supported video formats. ${err.message}'); - return; - } - console.log('Callback returned with supported video formats : ' + videoFormats.length); -}) -``` - -### getSupportedVideoFormats - -getSupportedVideoFormats\(\): Promise\> - -获取录制视频的支持格式,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -|--------------------------------|---------------------------------------------------| -| Promise\> | 使用Promise的方式获取支持的视频格式。 | - -**示例:** - -``` -cameraInput.getSupportedVideoFormats().then((videoFormats) => { - console.log('Promise returned with supported video formats.' + videoFormats.length); -}) -``` ### hasFlash @@ -610,9 +412,9 @@ hasFlash(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|-------------------------|-----------|----------------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,返回true表示设备支持闪光灯。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback | 是 | 回调函数,返回true表示设备支持闪光灯。 | **示例:** @@ -636,9 +438,9 @@ hasFlash(): Promise **返回值:** -| 类型 | 说明 | -|-----------------------|--------------------------------------------------------| -| Promise | 使用Promise的方式获取结果,返回true表示设备支持闪光灯。 | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持闪光灯。 | **示例:** @@ -658,10 +460,10 @@ isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): v **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|------------------------|-----------|----------------------------------------------------| -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | -| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ---------------------------------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该闪光灯模式。 | **示例:** @@ -685,15 +487,15 @@ isFlashModeSupported(flashMode: FlashMode): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|------------------------|-----------|----------------------------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ---------------- | | flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | **返回值:** -| 类型 | 说明 | -|-----------------------|---------------------------------------------------| -| Promise | 使用Promise的方式获取结果,返回true表示设备支持该闪光灯模式。 | +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持该闪光灯模式。 | **示例:** @@ -718,10 +520,10 @@ setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|------------------------|-----------|----------------------------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ------------------------ | | flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -750,15 +552,15 @@ setFlashMode(flashMode: FlashMode): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|------------------------|-----------|----------------------------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ---------------- | | flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | **返回值:** -| 类型 | 说明 | -|-----------------------|-----------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -778,9 +580,9 @@ getFlashMode(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|---------------------------|-----------|------------------------------------------------| -| callback | AsyncCallback<[FlashMode](#flashmode)\> | 是 | 回调函数,用于获取当前设备的闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback<[FlashMode](#flashmode)\> | 是 | 回调函数,用于获取当前设备的闪光灯模式。 | **示例:** @@ -804,9 +606,9 @@ getFlashMode(): Promise **返回值:** -| 类型 | 说明 | -|-----------------------|---------------------------------------------------| -| Promise<[FlashMode](#flashmode)\> | 使用Promise的方式获取当前的闪光灯模式。 | +| 类型 | 说明 | +| --------------------------------- | --------------------------------------- | +| Promise<[FlashMode](#flashmode)\> | 使用Promise的方式获取当前的闪光灯模式。 | **示例:** @@ -826,10 +628,10 @@ isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|------------------------|-----------|----------------------------------------------------| -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | -| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该焦距模式。 | **示例:** @@ -853,15 +655,15 @@ isFocusModeSupported(afMode: FocusMode): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|----------------------------------------|-----------|-------------| -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | **返回值:** -| 类型 | 说明 | -|-----------------------|---------------------------------------------------| -| Promise | 使用Promise的方式获取结果,返回true表示设备支持该焦距模式。 | +| 类型 | 说明 | +| ----------------- | ----------------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持该焦距模式。 | **示例:** @@ -883,10 +685,10 @@ setFocusMode(afMode: FocusMode, callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|------------------------|-----------|------------------------------------| -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------------ | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -912,15 +714,15 @@ setFocusMode(afMode: FocusMode): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|-----------------------------------------|-----------|-------------| -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | **返回值:** -| 类型 | 说明 | -|-----------------------|-----------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -940,9 +742,9 @@ getFocusMode(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|---------------------------|-----------|------------------------------------------------| -| callback | AsyncCallback<[FocusMode](#focusmode)\> | 是 | 回调函数,用于获取当前设备的焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback<[FocusMode](#focusmode)\> | 是 | 回调函数,用于获取当前设备的焦距模式。 | **示例:** @@ -988,9 +790,9 @@ getZoomRatioRange\(callback: AsyncCallback\>\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|--------------------------------|-----------|-------------------------------------------------| -| callback | AsyncCallback\> | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------ | ---- | ------------------------ | +| callback | AsyncCallback\> | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1014,8 +816,8 @@ getZoomRatioRange\(\): Promise\> **返回值:** -| 类型 | 说明 | -|------------------------|---------------------------------------------| +| 类型 | 说明 | +| ------------------------ | ------------------------------------------- | | Promise\> | 使用Promise的方式获取当前的可变焦距比范围。 | **示例:** @@ -1036,10 +838,10 @@ setZoomRatio(zoomRatio: number, callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|------------------------|-----------|------------------------------------| -| zoomRatio | number | 是 | 可变焦距比。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | -------------------- | ---- | ------------------------ | +| zoomRatio | number | 是 | 可变焦距比。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1063,15 +865,15 @@ setZoomRatio(zoomRatio: number): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|----------|-----------|-------------| -| zoomRatio | number | 是 | 可变焦距比。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ------------ | +| zoomRatio | number | 是 | 可变焦距比。 | **返回值:** -| 类型 | 说明 | -|-----------------------|-----------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1091,9 +893,9 @@ getZoomRatio(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-----------|---------------------------|-----------|------------------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1139,9 +941,9 @@ release\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1165,9 +967,9 @@ release(): Promise **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1187,10 +989,10 @@ on(type: 'focusStateChange', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'focusStateChange',即焦距状态变化事件。 | -| callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :---------------------------------------- | :--- | :------------------------------------------------------- | +| type | string | 是 | 监听事件,固定为'focusStateChange',即焦距状态变化事件。 | +| callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 | **示例:** @@ -1210,10 +1012,10 @@ on('error', callback: ErrorCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'error'。 | -| callback | ErrorCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :------------------------------- | :--- | :------------------------ | +| type | string | 是 | 监听事件,固定为'error'。 | +| callback | ErrorCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1228,33 +1030,39 @@ cameraInput.on('error', (cameraInputError) => { 枚举,闪光灯模式。 -| 名称 | 默认值 | 说明 | -|------------------------|---------------|------------------------| -| FLASH_MODE_CLOSE | 0 | 闪光灯关闭。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| FLASH_MODE_OPEN | 1 | 闪光灯开启。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| FLASH_MODE_AUTO | 2 | 自动闪光灯。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| FLASH_MODE_ALWAYS_OPEN | 3 | 闪光灯常亮。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| ---------------------- | ------ | ------------ | +| FLASH_MODE_CLOSE | 0 | 闪光灯关闭。 | +| FLASH_MODE_OPEN | 1 | 闪光灯开启。 | +| FLASH_MODE_AUTO | 2 | 自动闪光灯。 | +| FLASH_MODE_ALWAYS_OPEN | 3 | 闪光灯常亮。 | ## FocusMode 枚举,焦距模式。 -| 名称 | 默认值 | 说明 | -|----------------------------|---------------|----------------------------| -| FOCUS_MODE_MANUAL | 0 | 手动变焦模式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| FOCUS_MODE_CONTINUOUS_AUTO | 1 | 连续自动变焦模式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| FOCUS_MODE_AUTO | 2 | 自动变焦模式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| FOCUS_MODE_LOCKED | 3 | 定焦模式。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| -------------------------- | ------ | ------------------ | +| FOCUS_MODE_MANUAL | 0 | 手动变焦模式。 | +| FOCUS_MODE_CONTINUOUS_AUTO | 1 | 连续自动变焦模式。 | +| FOCUS_MODE_AUTO | 2 | 自动变焦模式。 | +| FOCUS_MODE_LOCKED | 3 | 定焦模式。 | ## FocusState 枚举,焦距状态。 -| 名称 | 默认值 | 说明 | -| --------------------- | ------ | ------------------------------------------------------------ | -| FOCUS_STATE_SCAN | 0 | 扫描状态。
系统能力 : SystemCapability.Multimedia.Camera.Core | -| FOCUS_STATE_FOCUSED | 1 | 相机已对焦。
系统能力 : SystemCapability.Multimedia.Camera.Core | -| FOCUS_STATE_UNFOCUSED | 2 | 相机未对焦。
系统能力 : SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| --------------------- | ------ | ------------ | +| FOCUS_STATE_SCAN | 0 | 扫描状态。 | +| FOCUS_STATE_FOCUSED | 1 | 相机已对焦。 | +| FOCUS_STATE_UNFOCUSED | 2 | 相机未对焦。 | ## camera.createCaptureSession @@ -1266,10 +1074,10 @@ createCaptureSession\(context: Context, callback: AsyncCallback **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|--------------------------------|-----------|-----------------------------------------------------| -| context | Context | 是 | 应用上下文。 | -| callback | AsyncCallback<[CaptureSession](#capturesession)\> | 是 | 回调函数,用于获取CaptureSession实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | -------------------------------------- | +| context | Context | 是 | 应用上下文。 | +| callback | AsyncCallback<[CaptureSession](#capturesession)\> | 是 | 回调函数,用于获取CaptureSession实例。 | **示例:** @@ -1293,14 +1101,14 @@ createCaptureSession(context: Context\): Promise; **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|-------------------------------|-----------|-----------------------------------------------------| -| context | Context | 是 | 应用上下文。 | +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------ | +| context | Context | 是 | 应用上下文。 | **返回值:** -| 类型 | 说明 | -|---------------------------|---------------------------------------------------| +| 类型 | 说明 | +| ------------------------------------------- | ----------------------------------------- | | Promise<[CaptureSession](#capturesession)\> | 使用Promise的方式获取CaptureSession实例。 | **示例:** @@ -1325,9 +1133,9 @@ beginConfig\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1351,9 +1159,9 @@ beginConfig\(\): Promise **返回值:** -| 类型 | 说明 | -|---------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1374,9 +1182,9 @@ commitConfig\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|---------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1400,9 +1208,9 @@ commitConfig\(\): Promise **返回值:** -| 类型 | 说明 | -|---------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1422,10 +1230,10 @@ addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-------------|----------------------|-----------|---------------------------------------------| -| cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1449,14 +1257,14 @@ addInput\(cameraInput: CameraInput\): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-------------|---------------------|-----------|-------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | | cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | **返回值:** -| 类型 | 说明 | -|----------------|------------------------------------| +| 类型 | 说明 | +| -------------- | --------------------------- | | Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1477,10 +1285,10 @@ addOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|----------------------|-----------|-------------------------------------| -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的PreviewOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ----------------------------- | +| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的PreviewOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1504,14 +1312,14 @@ addOutput\(previewOutput: PreviewOutput\): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|---------------------|-----------|--------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ----------------------------- | | previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的PreviewOutput实例。 | **返回值:** -| 类型 | 说明 | -|----------------|-----------------------------------| +| 类型 | 说明 | +| -------------- | --------------------------- | | Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1532,10 +1340,10 @@ addOutput\(photoOutput: PhotoOutput, callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|---------------------|-----------|-------------------------------------| -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1559,14 +1367,14 @@ addOutput\(photoOutput: PhotoOutput\): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|---------------------|-----------|--------------------------------| -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | **返回值:** -| 类型 | 说明 | -|---------------|-----------------------------------| +| 类型 | 说明 | +| -------------- | --------------------------- | | Promise\ | 使用Promise的方式获取结果。 | **示例:** @@ -1587,9 +1395,9 @@ addOutput\(videoOutput: VideoOutput, callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|---------------------|-----------|-------------------------------------| -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1642,10 +1450,10 @@ removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-------------|----------------------|-----------|------------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | | cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1669,14 +1477,14 @@ removeInput\(cameraInput: CameraInput\): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|-------------|---------------------|-----------|---------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | | cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | **返回值:** -| 类型 | 说明 | -|----------------|-----------------------------------| +| 类型 | 说明 | +| -------------- | --------------------------- | | Promise\ | 使用Promise的方式获取结果。 | **示例:** @@ -1697,10 +1505,10 @@ removeOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): vo **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|----------------------|-----------|------------------------------------| -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的PreviewOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ----------------------------- | +| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的PreviewOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1724,15 +1532,15 @@ removeOutput(previewOutput: PreviewOutput): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|---------------------|-----------|-----------------------------------| +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ----------------------------- | | previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的PreviewOutput实例。 | **返回值:** -| 类型 | 说明 | -|---------------|---------------------------------------------| +| 类型 | 说明 | +| -------------- | --------------------------- | | Promise | 使用Promise的方式获取结果。 | @@ -1754,10 +1562,10 @@ removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|----------------------|-----------|------------------------------------| -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1781,16 +1589,16 @@ removeOutput(photoOutput: PhotoOutput): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|---------------------|-----------|---------------------------------| -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | **返回值:** -| 类型 | 说明 | -|---------------|------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1811,10 +1619,10 @@ removeOutput(videoOutput: VideoOutput, callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|----------------------|-----------|------------------------------------| -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1838,16 +1646,16 @@ removeOutput(videoOutput: VideoOutput): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|---------------|---------------------|-----------|---------------------------------| -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | --------------------------- | +| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1868,9 +1676,9 @@ start\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1894,9 +1702,9 @@ start\(\): Promise **返回值:** -| 类型 | 说明 | -|----------------|-----------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1917,9 +1725,9 @@ stop\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1943,9 +1751,9 @@ stop(): Promise **返回值:** -| 类型 | 说明 | -|----------------|-----------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1965,9 +1773,9 @@ release\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1991,9 +1799,9 @@ release(): Promise **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -2013,10 +1821,10 @@ on(type: 'error', callback: ErrorCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'error'。 | -| callback | ErrorCallback | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :---------------------------------- | :--- | :--------------------------- | +| type | string | 是 | 监听事件,固定为'error'。 | +| callback | ErrorCallback | 是 | 回调函数,用于获取错误信息。 | **示例:** @@ -2036,10 +1844,10 @@ createPreviewOutput(surfaceId: string, callback: AsyncCallback): **参数:** -| 名称 | 类型 | 必填 | 说明 | -|------------|-------------------------------|-----------|----------------------------------------------------| -| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------------------------------- | ---- | ------------------------------------- | +| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。 | **示例:** @@ -2063,15 +1871,15 @@ createPreviewOutput(surfaceId: string): Promise\ **参数:** -| 名称 | 类型 | 必填 | 说明 | -|------------|-----------------|-----------|----------------------------------------------------| -| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------------------------------- | +| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | **返回值:** -| 类型 | 说明 | -|-------------------------|---------------------------------------------------| -| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ----------------------------------------- | --------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取结果。 | **示例:** @@ -2095,9 +1903,9 @@ release(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2121,9 +1929,9 @@ release(): Promise **返回值:** -| 类型 | 说明 | -|----------------|-----------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -2144,10 +1952,10 @@ on(type: 'frameStart', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------- | :-------- | :----------------------------------| -| type | string | 是 | 监听事件,固定为'frameStart',即帧启动事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :------------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',即帧启动事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2167,10 +1975,10 @@ on(type: 'frameEnd', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------- | :-------- | :----------------------------------| -| type | string | 是 | 监听事件,固定为'frameEnd',即帧结束事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameEnd',即帧结束事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2190,10 +1998,10 @@ on(type: 'error', callback: ErrorCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'error'。 | -| callback | ErrorCallback | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------- | :--- | :--------------------------- | +| type | string | 是 | 监听事件,固定为'error'。 | +| callback | ErrorCallback | 是 | 回调函数,用于获取错误信息。 | **示例:** @@ -2213,10 +2021,10 @@ createPhotoOutput(surfaceId: string, callback: AsyncCallback): voi **参数:** -| 名称 | 类型 | 必填 | 说明 | -|------------|-------------------------------|-----------|----------------------------------------------------| -| surfaceId | string | 是 | 从ImageReceiver获取的Surface ID。 | -| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | 是 | 回调函数,用于获取PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------- | ---- | ----------------------------------- | +| surfaceId | string | 是 | 从ImageReceiver获取的Surface ID。 | +| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | 是 | 回调函数,用于获取PhotoOutput实例。 | **示例:** @@ -2240,15 +2048,15 @@ createPhotoOutput(surfaceId: string): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|------------|-----------------|-----------|----------------------------------------------------| -| surfaceId | string | 是 | 从ImageReceiver获取的Surface ID。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------------------------------- | +| surfaceId | string | 是 | 从ImageReceiver获取的Surface ID。 | **返回值:** -| 类型 | 说明 | -|-------------------------|--------------------------------------------------| -| Promise<[PhotoOutput](#photooutput)\> | 使用Promise的方式获取PhotoOutput实例。 | +| 类型 | 说明 | +| ------------------------------------- | -------------------------------------- | +| Promise<[PhotoOutput](#photooutput)\> | 使用Promise的方式获取PhotoOutput实例。 | **示例:** @@ -2261,32 +2069,38 @@ camera.createPhotoOutput(surfaceId).then((photoOutput) => { 枚举,图片旋转角度。 -| 名称 | 默认值 | 说明 | -|--------------|---------------|----------------------------------------| -| ROTATION_0 | 0 | 图片旋转0度。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| ROTATION_90 | 90 | 图片旋转90度。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| ROTATION_180 | 180 | 图片旋转180度。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| ROTATION_270 | 270 | 图片旋转270度。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| ------------ | ------ | --------------- | +| ROTATION_0 | 0 | 图片旋转0度。 | +| ROTATION_90 | 90 | 图片旋转90度。 | +| ROTATION_180 | 180 | 图片旋转180度。 | +| ROTATION_270 | 270 | 图片旋转270度。 | ## QualityLevel 枚举,图片质量。 -| 名称 | 默认值 | 说明 | -|----------------------|---------------|----------------------| -| QUALITY_LEVEL_HIGH | 0 | 图片质量高。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| QUALITY_LEVEL_MEDIUM | 1 | 图片质量中等。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| QUALITY_LEVEL_LOW | 2 | 图片质量差。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 默认值 | 说明 | +| -------------------- | ------ | -------------- | +| QUALITY_LEVEL_HIGH | 0 | 图片质量高。 | +| QUALITY_LEVEL_MEDIUM | 1 | 图片质量中等。 | +| QUALITY_LEVEL_LOW | 2 | 图片质量差。 | ## PhotoCaptureSetting 拍摄照片的设置。 -| 名称 | 类型 | 必填 | 说明 | -|----------|---------------|-----------|---------------------| -| quality | [QualityLevel](#qualitylevel) | 否 | 图片质量。
**系统能力:** SystemCapability.Multimedia.Camera.Core | -| rotation | [ImageRotation](#imagerotation) | 否 | 图片旋转角度。
**系统能力:** SystemCapability.Multimedia.Camera.Core | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | -------------- | +| quality | [QualityLevel](#qualitylevel) | 否 | 图片质量。 | +| rotation | [ImageRotation](#imagerotation) | 否 | 图片旋转角度。 | ## PhotoOutput @@ -2303,9 +2117,9 @@ capture(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|---------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2329,10 +2143,10 @@ capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ------------------------ | +| setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2356,15 +2170,15 @@ capture(setting?: PhotoCaptureSetting): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|---------------------|-----------|----------------------------------------------| -| setting | [PhotoCaptureSetting](#photocapturesetting) | 否 | 拍照设置。 | +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------- | ---- | ---------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | 否 | 拍照设置。 | **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -2385,9 +2199,9 @@ release(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2411,9 +2225,9 @@ release(): Promise **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -2434,10 +2248,10 @@ on(type: 'captureStart', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'captureStart',即拍照启动事件。 | -| callback | AsyncCallback | 是 | 使用callback的方式获取Capture ID。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :--------------------- | :--- | :----------------------------------------------- | +| type | string | 是 | 监听事件,固定为'captureStart',即拍照启动事件。 | +| callback | AsyncCallback | 是 | 使用callback的方式获取Capture ID。 | **示例:** @@ -2457,10 +2271,10 @@ on(type: 'frameShutter', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'frameShutter',即帧刷新事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取相关信息。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :------------------------------- | :--- | :--------------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameShutter',即帧刷新事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取相关信息。 | **示例:** @@ -2481,10 +2295,10 @@ on(type: 'captureEnd', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'captureEnd',即拍照停止事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取相关信息。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :----------------------------- | :--- | :--------------------------------------------- | +| type | string | 是 | 监听事件,固定为'captureEnd',即拍照停止事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取相关信息。 | **示例:** @@ -2505,10 +2319,10 @@ on(type: 'error', callback: ErrorCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'error'。 | -| callback | ErrorCallback | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :------------------------------- | :--- | :--------------------------- | +| type | string | 是 | 监听事件,固定为'error'。 | +| callback | ErrorCallback | 是 | 回调函数,用于获取错误信息。 | **示例:** @@ -2528,10 +2342,10 @@ createVideoOutput(surfaceId: string, callback: AsyncCallback): voi **参数:** -| 名称 | 类型 | 必填 | 说明 | -|------------|-------------------------------|-----------|----------------------------------------------------| -| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | -| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------- | ---- | ----------------------------------- | +| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | +| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 | **示例:** @@ -2555,9 +2369,9 @@ createVideoOutput(surfaceId: string): Promise **参数:** -| 名称 | 类型 | 必填 | 说明 | -|------------|-----------------|-----------|----------------------------------------------------| -| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------------------------------- | +| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | **返回值:** @@ -2587,9 +2401,9 @@ start(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2613,9 +2427,9 @@ start(): Promise **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -2636,9 +2450,9 @@ stop(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2662,9 +2476,9 @@ stop(): Promise **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -2684,9 +2498,9 @@ release(callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -|----------|----------------------|-----------|----------------------------------------------| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2710,9 +2524,9 @@ release(): Promise **返回值:** -| 类型 | 说明 | -|----------------|---------------------------------------------| -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** @@ -2733,10 +2547,10 @@ on(type: 'frameStart', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------- | :-------- | :----------------------------------| -| type | string | 是 | 监听事件,固定为'frameStart',即视频帧开启事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',即视频帧开启事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2756,10 +2570,10 @@ on(type: 'frameEnd', callback: AsyncCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------- | :-------- | :----------------------------------| -| type | string | 是 | 监听事件,固定为'frameEnd',即视频帧结束事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :--------------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameEnd',即视频帧结束事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -2779,10 +2593,10 @@ on(type: 'error', callback: ErrorCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :-------- | :-----------------------------------------------| -| type | string | 是 | 监听事件,固定为'error'。 | -| callback | Callback | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| :------- | :-------------------------- | :--- | :--------------------------- | +| type | string | 是 | 监听事件,固定为'error'。 | +| callback | Callback | 是 | 回调函数,用于获取错误信息。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md index d7fad75e68111100e32c4fc02cd4c0a2ddc05c3e..84d4426f00f65412b4c8d53cf282eb7fd07239e7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @@ -15,10 +15,12 @@ import data_Preferences from '@ohos.data.preferences' ## 属性 +**系统能力**:以下各项对应的系统能力均为SystemCapability.DistributedDataManager.Preferences.Core + | 名称 | 参数类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | 是 | 否 | key的最大长度限制,大小为80字节。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core | -| MAX_VALUE_LENGTH | string | 是 | 否 | string类型value的最大长度限制,大小为8192字节。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core | +| MAX_KEY_LENGTH | string | 是 | 否 | key的最大长度限制,大小为80字节。 | +| MAX_VALUE_LENGTH | string | 是 | 否 | string类型value的最大长度限制,大小为8192字节。 | ## data_Preferences.getPreferences @@ -77,8 +79,8 @@ getPreferences(context: Context, name: string): Promise<Preferences> import Ability from '@ohos.application.Ability' import data_Preferences from '@ohos.data.preferences' var path = this.context.getDataBaseDir() - let promise = data_Preferences.getPreferences(this.context, 'mystore') - promise.then((preferences) => { + let promisePre = data_Preferences.getPreferences(this.context, 'mystore') + promisePre.then((preferences) => { preferences.putSync('startup', 'auto') preferences.flushSync() }).catch((err) => { @@ -89,7 +91,7 @@ getPreferences(context: Context, name: string): Promise<Preferences> ## data_Preferences.deletePreferences -deletePreferences(context: Context, name: string, callback: AsyncCallback<void>) +deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void 从内存中移除指定文件对应的Preferences单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题,使用callback方式作为异步方法。 @@ -139,8 +141,8 @@ deletePreferences(context: Context, name: string): Promise<void> ``` import Ability from '@ohos.application.Ability' import data_Preferences from '@ohos.data.preferences' - let promise = data_Preferences.deletePreferences(this.context, 'mystore') - promise.then(() => { + let promisedelPre = data_Preferences.deletePreferences(this.context, 'mystore') + promisedelPre.then(() => { console.info("Deleted successfully.") }).catch((err) => { console.info("Deleted failed with err: " + err) @@ -150,7 +152,7 @@ deletePreferences(context: Context, name: string): Promise<void> ## data_Preferences.removePreferencesFromCache -removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<Preferences>): void +removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void 从内存中移除指定文件对应的Preferences单实例。移除Preferences单实例时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题。 @@ -163,7 +165,7 @@ removePreferencesFromCache(context: Context, name: string, callback: AsyncCallba | -------- | -------- | -------- | -------- | | context | Context | 是 | 应用程序或功能的上下文 | | name | string | 是 | 应用程序内部数据存储名称。 | - | callback | AsyncCallback<[Preferences](#preferences)> | 是 | 回调函数。 | + | callback | AsyncCallback<void> | 是 | 回调函数。 | - 示例: ``` @@ -204,8 +206,8 @@ removePreferencesFromCache(context: Context, name: string): Promise<void> ``` import Ability from '@ohos.application.Ability' import data_Preferences from '@ohos.data.preferences' - let promise = data_Preferences.removePreferencesFromCache(this.context, 'mystore') - promise.then(() => { + let promiserevPre = data_Preferences.removePreferencesFromCache(this.context, 'mystore') + promiserevPre.then(() => { console.info("Removed preferences from cache successfully.") }).catch((err) => { console.info("Removed preferences from cache failed with err: " + err) @@ -270,8 +272,8 @@ get(key: string, defValue: ValueType): Promise<ValueType> - 示例: ``` - let promise = preferences.get('startup', 'default') - promise.then((value) => { + let promiseget = preferences.get('startup', 'default') + promiseget.then((value) => { console.info("The value of startup is " + value) }).catch((err) => { console.info("Get the value of startup failed with err: " + err) @@ -331,8 +333,8 @@ put(key: string, value: ValueType): Promise<void> - 示例: ``` - let promise = preferences.put('startup', 'auto') - promise.then(() => { + let promiseput = preferences.put('startup', 'auto') + promiseput.then(() => { console.info("Put the value of startup successfully.") }).catch((err) => { console.info("Put the value of startup failed with err: " + err) @@ -397,8 +399,8 @@ has(key: string): Promise<boolean> - 示例: ``` - let promise = preferences.has('startup') - promise.then((isExist) => { + let promisehas = preferences.has('startup') + promisehas.then((isExist) => { if (isExist) { console.info("The key of startup is contained.") } @@ -458,8 +460,8 @@ delete(key: string): Promise<void> - 示例: ``` - let promise = preferences.delete('startup') - promise.then(() => { + let promisedel = preferences.delete('startup') + promisedel.then(() => { console.info("Deleted startup key successfully.") }).catch((err) => { console.info("Delete startup key failed with err: " + err) @@ -511,8 +513,8 @@ flush(): Promise<void> - 示例: ``` - let promise = preferences.flush() - promise.then(() => { + let promiseflush = preferences.flush() + promiseflush.then(() => { console.info("Flushed to file successfully.") }).catch((err) => { console.info("Flush to file failed with err: " + err) @@ -564,8 +566,8 @@ clear(): Promise<void> - 示例: ``` - let promise = preferences.clear() - promise.then(() => { + let promiseclear = preferences.clear() + promiseclear.then(() => { console.info("Cleared to file successfully.") }).catch((err) => { console.info("Clear to file failed with err: " + err) diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md index 8bfce043074d777f72856870b995d8d508dcfbe9..04b1695912e16df298266993d9be52bc239bc008 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md @@ -4,7 +4,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 从API Version 9开始,该接口不再维护,推荐使用新接口 [@ohos.data.preferences](js-apis-data-preferences.md) +> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
从API Version 9开始,该接口不再维护,推荐使用新接口 [@ohos.data.preferences](js-apis-data-preferences.md) ## 导入模块 @@ -13,25 +13,24 @@ import dataStorage from '@ohos.data.storage' ``` -## 系统能力 -SystemCapability.DistributedDataManager.Preferences.Core - - - ## 属性 +**系统能力**:以下各项对应的系统能力均为SystemCapability.DistributedDataManager.Preferences.Core + | 名称 | 参数类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | MAX_KEY_LENGTH | string | 是 | 否 | key的最大长度限制,大小为80字节。 | | MAX_VALUE_LENGTH | string | 是 | 否 | string类型value的最大长度限制,大小为8192字节。 | -## dataStorage.getStorageSync(deprecated) +## dataStorage.getStorageSync getStorageSync(path: string): Storage 读取指定文件,将数据加载到Storage实例,用于数据操作,此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -55,12 +54,14 @@ getStorageSync(path: string): Storage ``` -## dataStorage.getStorage(deprecated) +## dataStorage.getStorage getStorage(path: string, callback: AsyncCallback<Storage>): void 读取指定文件,将数据加载到Storage实例,用于数据操作,使用callback形式返回结果。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -85,12 +86,14 @@ getStorage(path: string, callback: AsyncCallback<Storage>): void ``` -## dataStorage.getStorage(deprecated) +## dataStorage.getStorage getStorage(path: string): Promise<Storage> 读取指定文件,将数据加载到Storage实例,用于数据操作,使用Promise方式作为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -108,8 +111,8 @@ getStorage(path: string): Promise<Storage> var context = featureAbility.getContext() var path = await context.getFilesDir() - let promise = dataStorage.getStorage(path + '/mystore') - promise.then((storage) => { + let promisegetSt = dataStorage.getStorage(path + '/mystore') + promisegetSt.then((storage) => { storage.putSync('startup', 'auto') storage.flushSync() }).catch((err) => { @@ -118,12 +121,14 @@ getStorage(path: string): Promise<Storage> ``` -## dataStorage.deleteStorageSync(deprecated) +## dataStorage.deleteStorageSync deleteStorageSync(path: string): void 从内存中移除指定文件对应的Storage单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题,此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -135,12 +140,14 @@ deleteStorageSync(path: string): void ``` -## dataStorage.deleteStorage(deprecated) +## dataStorage.deleteStorage -deleteStorage(path: string, callback: AsyncCallback<void>) +deleteStorage(path: string, callback: AsyncCallback<void>): void 从内存中移除指定文件对应的Storage单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题,使用callback方式作为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -159,12 +166,14 @@ deleteStorage(path: string, callback: AsyncCallback<void>) ``` -## dataStorage.deleteStorage(deprecated) +## dataStorage.deleteStorage deleteStorage(path: string): Promise<void> 从内存中移除指定文件对应的Storage单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题,使用promise方式作为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -177,8 +186,8 @@ deleteStorage(path: string): Promise<void> - 示例: ``` - let promise = dataStorage.deleteStorage(path + '/mystore') - promise.then(() => { + let promisedelSt = dataStorage.deleteStorage(path + '/mystore') + promisedelSt.then(() => { console.info("Deleted successfully.") }).catch((err) => { console.info("Deleted failed with err: " + err) @@ -186,7 +195,7 @@ deleteStorage(path: string): Promise<void> ``` -## dataStorage.removeStorageFromCacheSync(deprecated) +## dataStorage.removeStorageFromCacheSync removeStorageFromCacheSync(path: string): void @@ -194,6 +203,8 @@ removeStorageFromCacheSync(path: string): void 此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -205,19 +216,21 @@ removeStorageFromCacheSync(path: string): void ``` -## dataStorage.removeStorageFromCache(deprecated) +## dataStorage.removeStorageFromCache -removeStorageFromCache(path: string, callback: AsyncCallback<Storage>): void +removeStorageFromCache(path: string, callback: AsyncCallback<void>): void 从内存中移除指定文件对应的Storage单实例。移除Storage单实例时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题。 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | path | string | 是 | 应用程序内部数据存储路径。 | - | callback | AsyncCallback<[Storage](#storage)> | 是 | 回调函数。 | + | callback | AsyncCallback<void> | 是 | 回调函数。 | - 示例: ``` @@ -231,7 +244,7 @@ removeStorageFromCache(path: string, callback: AsyncCallback<Storage>): vo ``` -## dataStorage.removeStorageFromCache(deprecated) +## dataStorage.removeStorageFromCache removeStorageFromCache(path: string): Promise<void> @@ -239,6 +252,8 @@ removeStorageFromCache(path: string): Promise<void> 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -251,8 +266,8 @@ removeStorageFromCache(path: string): Promise<void> - 示例: ``` - let promise = dataStorage.removeStorageFromCache(path + '/mystore') - promise.then(() => { + let promiserevSt = dataStorage.removeStorageFromCache(path + '/mystore') + promiserevSt.then(() => { console.info("Removed storage from cache successfully.") }).catch((err) => { console.info("Removed storage from cache failed with err: " + err) @@ -260,12 +275,12 @@ removeStorageFromCache(path: string): Promise<void> ``` -## Storage(deprecated) +## Storage 提供获取和修改存储数据的接口。 -### getSync(deprecated) +### getSync getSync(key: string, defValue: ValueType): ValueType @@ -273,6 +288,8 @@ getSync(key: string, defValue: ValueType): ValueType 此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -291,7 +308,7 @@ getSync(key: string, defValue: ValueType): ValueType ``` -### get(deprecated) +### get get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void @@ -299,6 +316,8 @@ get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -318,7 +337,7 @@ get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): ``` -### get(deprecated) +### get get(key: string, defValue: ValueType): Promise<ValueType> @@ -326,6 +345,8 @@ get(key: string, defValue: ValueType): Promise<ValueType> 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -339,8 +360,8 @@ get(key: string, defValue: ValueType): Promise<ValueType> - 示例: ``` - let promise = storage.get('startup', 'default') - promise.then((value) => { + let promiseget = storage.get('startup', 'default') + promiseget.then((value) => { console.info("The value of startup is " + value) }).catch((err) => { console.info("Get the value of startup failed with err: " + err) @@ -348,7 +369,7 @@ get(key: string, defValue: ValueType): Promise<ValueType> ``` -### putSync(deprecated) +### putSync putSync(key: string, value: ValueType): void @@ -356,6 +377,8 @@ putSync(key: string, value: ValueType): void 此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -368,7 +391,7 @@ putSync(key: string, value: ValueType): void ``` -### put(deprecated) +### put put(key: string, value: ValueType, callback: AsyncCallback<void>): void @@ -376,6 +399,8 @@ put(key: string, value: ValueType, callback: AsyncCallback<void>): void 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -395,7 +420,7 @@ put(key: string, value: ValueType, callback: AsyncCallback<void>): void ``` -### put(deprecated) +### put put(key: string, value: ValueType): Promise<void> @@ -403,6 +428,8 @@ put(key: string, value: ValueType): Promise<void> 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -416,8 +443,8 @@ put(key: string, value: ValueType): Promise<void> - 示例: ``` - let promise = storage.put('startup', 'auto') - promise.then(() => { + let promiseput = storage.put('startup', 'auto') + promiseput.then(() => { console.info("Put the value of startup successfully.") }).catch((err) => { console.info("Put the value of startup failed with err: " + err) @@ -425,7 +452,7 @@ put(key: string, value: ValueType): Promise<void> ``` -### hasSync(deprecated) +### hasSync hasSync(key: string): boolean @@ -433,6 +460,8 @@ hasSync(key: string): boolean 此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -452,7 +481,7 @@ hasSync(key: string): boolean ``` -### has(deprecated) +### has has(key: string, callback: AsyncCallback<boolean>): boolean @@ -460,6 +489,8 @@ has(key: string, callback: AsyncCallback<boolean>): boolean 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -485,7 +516,7 @@ has(key: string, callback: AsyncCallback<boolean>): boolean ``` -### has(deprecated) +### has has(key: string): Promise<boolean> @@ -493,6 +524,8 @@ has(key: string): Promise<boolean> 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -505,8 +538,8 @@ has(key: string): Promise<boolean> - 示例: ``` - let promise = storage.has('startup') - promise.then((isExist) => { + let promisehas = storage.has('startup') + promisehas.then((isExist) => { if (isExist) { console.info("The key of startup is contained.") } @@ -516,7 +549,7 @@ has(key: string): Promise<boolean> ``` -### deleteSync(deprecated) +### deleteSync deleteSync(key: string): void @@ -524,6 +557,8 @@ deleteSync(key: string): void 此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -535,7 +570,7 @@ deleteSync(key: string): void ``` -### delete(deprecated) +### delete delete(key: string, callback: AsyncCallback<void>): void @@ -543,6 +578,8 @@ delete(key: string, callback: AsyncCallback<void>): void 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -561,7 +598,7 @@ delete(key: string, callback: AsyncCallback<void>): void ``` -### delete(deprecated) +### delete delete(key: string): Promise<void> @@ -569,6 +606,8 @@ delete(key: string): Promise<void> 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -581,8 +620,8 @@ delete(key: string): Promise<void> - 示例: ``` - let promise = storage.delete('startup') - promise.then(() => { + let promisedel = storage.delete('startup') + promisedel.then(() => { console.info("Deleted startup key successfully.") }).catch((err) => { console.info("Delete startup key failed with err: " + err) @@ -590,7 +629,7 @@ delete(key: string): Promise<void> ``` -### flushSync(deprecated) +### flushSync flushSync(): void @@ -598,13 +637,15 @@ flushSync(): void 此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 示例: ``` storage.flushSync() ``` -### flush(deprecated) +### flush flush(callback: AsyncCallback<void>): void @@ -612,6 +653,8 @@ flush(callback: AsyncCallback<void>): void 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -629,7 +672,7 @@ flush(callback: AsyncCallback<void>): void ``` -### flush(deprecated) +### flush flush(): Promise<void> @@ -637,6 +680,8 @@ flush(): Promise<void> 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 返回值: | 类型 | 说明 | | -------- | -------- | @@ -644,8 +689,8 @@ flush(): Promise<void> - 示例: ``` - let promise = storage.flush() - promise.then(() => { + let promiseflush = storage.flush() + promiseflush.then(() => { console.info("Flushed to file successfully.") }).catch((err) => { console.info("Flush to file failed with err: " + err) @@ -653,7 +698,7 @@ flush(): Promise<void> ``` -### clearSync(deprecated) +### clearSync clearSync(): void @@ -661,13 +706,15 @@ clearSync(): void 此方法为同步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 示例: ``` storage.clearSync() ``` -### clear(deprecated) +### clear clear(callback: AsyncCallback<void>): void @@ -675,6 +722,8 @@ clear(callback: AsyncCallback<void>): void 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -692,7 +741,7 @@ clear(callback: AsyncCallback<void>): void ``` -### clear(deprecated) +### clear clear(): Promise<void> @@ -700,6 +749,8 @@ clear(): Promise<void> 此方法为异步方法。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 返回值: | 类型 | 说明 | | -------- | -------- | @@ -707,8 +758,8 @@ clear(): Promise<void> - 示例: ``` - let promise = storage.clear() - promise.then(() => { + let promiseclear = storage.clear() + promiseclear.then(() => { console.info("Cleared to file successfully.") }).catch((err) => { console.info("Clear to file failed with err: " + err) @@ -716,12 +767,14 @@ clear(): Promise<void> ``` -### on('change')(deprecated) +### on('change') on(type: 'change', callback: Callback<StorageObserver>): void 订阅数据变更者类需要实现StorageObserver接口,订阅的key的值发生变更后,在执行flush/flushSync方法后,callback方法会被回调。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 说明 | | -------- | -------- | -------- | @@ -739,12 +792,14 @@ on(type: 'change', callback: Callback<StorageObserver>): void ``` -### off('change')(deprecated) +### off('change') off(type: 'change', callback: Callback<StorageObserver>): void 当不再进行订阅数据变更时,使用此接口取消订阅。 +**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core + - 参数: | 参数名 | 类型 | 说明 | | -------- | -------- | -------- | @@ -760,7 +815,9 @@ off(type: 'change', callback: Callback<StorageObserver>): void ``` -## StorageObserver(deprecated) +## StorageObserver + +**系统能力**:以下各项对应的系统能力均为SystemCapability.DistributedDataManager.Preferences.Core | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-deque.md b/zh-cn/application-dev/reference/apis/js-apis-deque.md index 96440fe9281dd472232c783b28c2fe8e548ba431..7ad3b930f97b8503ac886f41e4c08cba42b9c759 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-deque.md +++ b/zh-cn/application-dev/reference/apis/js-apis-deque.md @@ -154,7 +154,6 @@ deque.insertEnd(4); deque.insertFront(5); deque.insertFront(2); deque.insertFront(4); -deque.popLast(); let result = deque.popLast(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md b/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md index 47e8f992081e49b0550e92361002062e6cda5c47..016db64b471b5e8fd04a20e70d3523850af0a365 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md @@ -811,7 +811,7 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY。 | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | 表示迁移是可拉回的。 | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | 如果未安装指定的功能,请安装该功能。 | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | 如果未安装,使用后台模式安装该功能。 | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | 指示清除其他任务的操作。可以为传递给**ohos.app.Context#startAbility**的**Want**设置此标志,并且必须与**flag_ABILITY_NEW_MISSION**一起使用。 | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | 指示清除其他任务的操作。可以为传递给 **[ohos.app.Context](js-apis-ability-context.md)** 中**startAbility**方法的**Want**设置此标志,并且必须与**flag_ABILITY_NEW_MISSION**一起使用。 | | FLAG_ABILITY_NEW_MISSION | 0x10000000 | 指示在历史任务堆栈上创建任务的操作。 | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | 指示如果启动能力的现有实例已位于任务堆栈的顶部,则将重用该实例。否则,将创建一个新的能力实例。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileio.md b/zh-cn/application-dev/reference/apis/js-apis-fileio.md index 1e6def6533c67181588eed4a966acda87a8f4311..df7bf37867a7410a18d2609db8255a90ce2d598e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileio.md @@ -760,7 +760,7 @@ rmdir(path: string, callback:AsyncCallback<void>): void ``` -## fileio.rmdirSync +## fileio.rmdirSync7+ rmdirSync(path: string): void diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md index 004c08485c77990b80c00b78192ce033e1a0f27d..7e2dfcf0d20fda4ea26e391b28752bf98fe8cc8a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md @@ -319,7 +319,7 @@ let result = hashMap.replace("sdfs", 357); ### forEach -forEach(callbackfn: (value: V, key?: K, map?: HashMap) => void, thisArg?: Object): void +forEach(callbackfn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void 通过回调函数来遍历HashMap实例对象上的元素以及元素对应的下标。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashset.md b/zh-cn/application-dev/reference/apis/js-apis-hashset.md index 8a0556e94cd954f73906bc690db303a03544b2b4..685929bfc3552b08ab982bd1c120c215f52b6f2b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashset.md @@ -184,7 +184,7 @@ while(temp != undefined) { ### forEach -forEach(callbackfn: (value: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void +forEach(callbackfn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void 通过回调函数来遍历实例对象上的元素以及元素对应的下标。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-i18n.md b/zh-cn/application-dev/reference/apis/js-apis-i18n.md index 9526ca700eff8b2620b1534285cc9fc65e94a337..2ea09cf3a29dd5a30359fc112f19828c3147de24 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-i18n.md +++ b/zh-cn/application-dev/reference/apis/js-apis-i18n.md @@ -67,7 +67,7 @@ getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): stri ``` -## i18n.isRTL8+ +## i18n.isRTL7+ isRTL(locale: string): boolean @@ -1258,7 +1258,7 @@ isBoundary(offset: number): boolean ``` -## i18n.is24HourClock8+ +## i18n.is24HourClock7+ is24HourClock(): boolean @@ -1277,7 +1277,7 @@ is24HourClock(): boolean ``` -## i18n.set24HourClock8+ +## i18n.set24HourClock7+ set24HourClock(option: boolean): boolean @@ -1394,7 +1394,7 @@ getFirstPreferredLanguage(): string ``` -## i18n.getTimeZone8+ +## i18n.getTimeZone7+ getTimeZone(zoneID?: string): TimeZone diff --git a/zh-cn/application-dev/reference/apis/js-apis-intl.md b/zh-cn/application-dev/reference/apis/js-apis-intl.md index 811318e13a89e9503d27eec24cababc55f67d5ad..9d4ea8f9485858d7c6338f0f222252a416512718 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-intl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-intl.md @@ -1,7 +1,7 @@ # 国际化-Intl > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > > - Intl模块包含国际化能力基础接口(在ECMA 402中定义)。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md index 8c8601d225c33bf5b768714c37ef4f355bf4f421..b9f1f17231c91aa76c470076941053c1a2e99bd9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @@ -510,7 +510,7 @@ while(temp != undefined) { ### forEach -forEach(callbackfn: (value: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void +forEach(callbackfn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void 通过回调函数来遍历实例对象上的元素以及元素对应的下标。 @@ -569,7 +569,7 @@ while(temp != undefined) { ### toString -toString(): string +toString(): String 将此映射中包含的键值对拼接成字符串,并返回字符串类型。 @@ -577,7 +577,7 @@ toString(): string | 类型 | 说明 | | -------- | -------- | - | string | 返回一个字符串。 | + | String | 返回一个字符串。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md index 66b3a24981a800cb85100c792df746b70b0e9f93..7703b787c86d4886a2e88dcef785ad9e34c3e22b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @@ -414,7 +414,7 @@ while(index < lightWeightSet.length) { ### forEach -forEach(callbackfn: (value: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void +forEach(callbackfn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void 通过回调函数来遍历LightWeightSet实例对象上的元素以及元素对应的下标。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md index a94ab6d6243484c5ad5b1d3914da713e75313fd3..a2b99e3f368bbee9dfc6961705e9aedade6ef3f3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -27,16 +27,10 @@ SystemCapability.Utils.Lang ### constructor -constructor(head?: NodeObj<T>, tail?: NodeObj<T>) +constructor() LinkedList的构造函数。 -**参数:** - -| 参数名 | 类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| head | NodeObj<T> | 是 | 否 | 节点对象,含有element、next指向和prev指向。 | -| tail | NodeObj<T> | 是 | 否 | 节点对象,含有element、next指向和prev指向。 | **示例:** @@ -300,7 +294,7 @@ let result = linkedList.removeFirst(); ### removeLast -removeLst(): T +removeLast(): T 删除并返回LinkedList的最后一个元素。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-list.md b/zh-cn/application-dev/reference/apis/js-apis-list.md index f8d0856f180ab2094985018341821a6585633786..31fdd3e13d0dfa95e7cae70b9db8e64b91826728 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-list.md +++ b/zh-cn/application-dev/reference/apis/js-apis-list.md @@ -27,15 +27,10 @@ SystemCapability.Utils.Lang ### constructor -constructor(head?: NodeObj<T>) +constructor() List的构造函数。 -**参数:** - -| 参数名 | 类型 | 可读 | 说明 | -| -------- | -------- | -------- | -------- | -| head | NodeObj<T> | 是 | 节点对象,含有element、next指向。 | **示例:** @@ -465,6 +460,7 @@ list.clear(); ### set set(index: number, element: T): T + 将此 List 中指定位置的元素替换为指定元素。 **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index 6a4e22478e61f31526cfd26beb260a035ec33e5a..fb20738b8dc2b278b5f7a706edc8b7d88d2dd46f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -10,7 +10,7 @@ - 音频播放([AudioPlayer](#audioplayer)) - 视频播放([VideoPlayer](#videoplayer8)) - 音频录制([AudioRecorder](#audiorecorder)) -- 视频录制([VideoRecorder](#VideoRecorder8+)) +- 视频录制([VideoRecorder](#videoRecorder8)) 后续将提供以下功能:DataSource音视频播放、音视频编解码、容器封装解封装、媒体能力查询等功能。 @@ -228,12 +228,16 @@ Codec MIME类型枚举。 **系统能力:** 以下各项对应的系统能力均为 SystemCapability.Multimedia.Media.Core。 -| 名称 | 值 | 说明 | -| ------------ | ----------------- | ------------------------ | -| VIDEO_MPEG4 | ”video/mp4v-es“ | 表示视频/mpeg4类型。 | -| AUDIO_AAC | "audio/mp4a-latm" | 表示音频/mp4a-latm类型。 | -| AUDIO_VORBIS | "audio/vorbis" | 表示音频/vorbis类型。 | -| AUDIO_FLAC | "audio/flac" | 表示音频/flac类型。 | +| 名称 | 值 | 说明 | +| ------------ | --------------------- | ------------------------ | +| VIDEO_H263 | 'video/h263' | 表示视频/h263类型。 | +| VIDEO_AVC | 'video/avc' | 表示视频/avc类型。 | +| VIDEO_MPEG2 | 'video/mpeg2' | 表示视频/mpeg2类型。 | +| VIDEO_MPEG4 | 'video/mp4v-es' | 表示视频/mpeg4类型。 | +| VIDEO_VP8 | 'video/x-vnd.on2.vp8' | 表示视频/vp8类型。 | +| AUDIO_AAC | "audio/mp4a-latm" | 表示音频/mp4a-latm类型。 | +| AUDIO_VORBIS | 'audio/vorbis' | 表示音频/vorbis类型。 | +| AUDIO_FLAC | 'audio/flac' | 表示音频/flac类型。 | ## MediaDescriptionKey8+ @@ -279,7 +283,7 @@ Codec MIME类型枚举。 | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | 是 | 是 | 音频媒体URI,支持当前主流的音频格式(mp4、aac、mp3、ogg)。
**支持路径示例**:
1. fd类型播放:fd://xxx
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
2. http网络播放路径:开发中
3. hls网络播放路径:开发中
**注意事项**:
使用媒体素材需要获取读权限,否则无法正常播放。 | +| src | string | 是 | 是 | 音频媒体URI,支持当前主流的音频格式(mp4、aac、mp3、ogg、wav)。
**支持路径示例**:
1、fd类型播放:fd://xx
![](figures/zh-cn_image_url.png)
2、http网络播放: http://xx
3、hls网络播放路径:开发中
**注意事项**:
使用媒体素材需要获取读权限,否则无法正常播放。 | | loop | boolean | 是 | 是 | 音频循环播放属性,设置为'true'表示循环播放。 | | currentTime | number | 是 | 否 | 音频的当前播放位置。 | | duration | number | 是 | 否 | 音频时长。 | @@ -289,7 +293,7 @@ Codec MIME类型枚举。 play(): void -开始播放音频资源,需在[dataLoad](#on('play' | 'pause' | 'stop' | 'reset' | 'dataload' | 'finish' | 'volumechange'))事件成功触发后,才能调用play方法。 +开始播放音频资源,需在[dataLoad](#audioplayer_on)事件成功触发后,才能调用play方法。 **系统能力:** SystemCapability.Multimedia.Media.AudioPlayer @@ -420,7 +424,7 @@ audioPlayer = undefined; ### getTrackDescription8+ -getTrackDescription(callback: AsyncCallback>): void +getTrackDescription(callback: AsyncCallback>): void 通过回调方式获取音频轨道信息。 @@ -456,7 +460,7 @@ audioPlayer.getTrackDescription((error, arrlist) => { ### getTrackDescription8+ -getTrackDescription(): Promise> +getTrackDescription(): Promise> 通过Promise方式获取音频轨道信息。 @@ -507,10 +511,10 @@ on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferingi **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 音频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | -| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | 是 | 音频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 音频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | +| callback | function | 是 | 音频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | **示例:** @@ -521,7 +525,7 @@ audioPlayer.on('bufferingUpdate', (infoType, value) => { }); ``` - ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') + ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void @@ -533,7 +537,7 @@ on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeCh | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。
- 'play':完成[play()](#play)调用,音频开始播放,触发该事件。
- 'pause':完成[pause()](#pause)调用,音频暂停播放,触发该事件。
- 'stop':完成[stop()](#stop)调用,音频停止播放,触发该事件。
- 'reset':完成[reset()](#reset7)调用,播放器重置,触发该事件。
- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。
- 'finish':完成音频播放后触发该事件。
- 'volumeChange':完成[setVolume()](#setvolume)调用,播放音量改变后触发该事件。 | +| type | string | 是 | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。
- 'play':完成[play()](#audioplayer_play)调用,音频开始播放,触发该事件。
- 'pause':完成[pause()](#audioplayer_pause)调用,音频暂停播放,触发该事件。
- 'stop':完成[stop()](#audioplayer_stop)调用,音频停止播放,触发该事件。
- 'reset':完成[reset()](#audioplayer_reset)调用,播放器重置,触发该事件。
- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。
- 'finish':完成音频播放后触发该事件。
- 'volumeChange':完成[setVolume()](#audioplayer_setvolume)调用,播放音量改变后触发该事件。 | | callback | () => void | 是 | 播放事件回调方法。 | **示例:** @@ -605,7 +609,7 @@ on(type: 'timeUpdate', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放事件回调类型,支持的事件包括:'timeUpdate'。
- 'timeUpdate':[seek()](#seek)调用完成,触发该事件。 | +| type | string | 是 | 播放事件回调类型,支持的事件包括:'timeUpdate'。
- 'timeUpdate':[seek()](#audioplayer_seek)调用完成,触发该事件。 | | callback | Callback\ | 是 | 播放事件回调方法。回调方法入参为成功seek的时间。 | **示例:** @@ -663,7 +667,7 @@ audioPlayer.setVolume(3); //设置volume为无效值,触发'error'事件 ## VideoPlayer8+ -视频播放管理类,用于管理和播放视频媒体。在调用VideoPlayer的方法前,需要先通过[createVideoPlayer()](#media.createvideoplayer8)构建一个[VideoPlayer](#videoplayer8)实例。 +视频播放管理类,用于管理和播放视频媒体。在调用VideoPlayer的方法前,需要先通过[createVideoPlayer()](#mediacreatevideoplayer8)构建一个[VideoPlayer](#videoplayer8)实例。 视频播放demo可参考:[视频播放开发指导](../../media/video-playback.md) @@ -673,7 +677,7 @@ audioPlayer.setVolume(3); //设置volume为无效值,触发'error'事件 | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | 是 | 是 | 视频媒体URL,支持当前主流的视频格式(mp4、mpeg-ts、webm、mkv)。
**支持路径示例**:
1. fd类型播放:fd://xxx
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
**注意事项**:
使用媒体素材需要获取读权限,否则无法正常播放。 | +| url8+ | string | 是 | 是 | 视频媒体URL,支持当前主流的视频格式(mp4、mpeg-ts、webm、mkv)。
**支持路径示例**:
1. fd类型播放:fd://xx
![](figures/zh-cn_image_url.png)
2、http网络播放: http://xx
3、hls网络播放路径:开发中
**注意事项**:
使用媒体素材需要获取读权限,否则无法正常播放。 | | loop8+ | boolean | 是 | 是 | 视频循环播放属性,设置为'true'表示循环播放。 | | currentTime8+ | number | 是 | 否 | 视频的当前播放位置。 | | duration8+ | number | 是 | 否 | 视频时长,返回-1表示直播模式。 | @@ -1049,11 +1053,11 @@ seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ---------------------------------------- | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | -| mode | SeekMode | 是 | 跳转模式,具体见[SeekMode](#seekmode8)。 | -| callback | function | 是 | 跳转到指定播放位置的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | +| mode | [SeekMode](#seekmode8) | 是 | 跳转模式。 | +| callback | function | 是 | 跳转到指定播放位置的回调方法。 | **示例:** @@ -1077,10 +1081,10 @@ seek(timeMs: number, mode?:SeekMode): Promise\ **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | -------- | ---- | -------------------------------------- | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | -| mode | SeekMode | 否 | 跳转模式,具体见[SeekMode](#seekmode8) | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------------- | ---- | ------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | +| mode | [SeekMode](#seekmode8) | 否 | 跳转模式。 | **返回值:** @@ -1223,7 +1227,7 @@ await videoPlayer.release().then() => { ### getTrackDescription8+ -getTrackDescription(callback: AsyncCallback>): void +getTrackDescription(callback: AsyncCallback>): void 通过回调方式获取视频轨道信息。 @@ -1231,9 +1235,9 @@ getTrackDescription(callback: AsyncCallback> | 是 | 获取视频轨道信息回调方法。 | **示例:** @@ -1259,7 +1263,7 @@ videoPlayer.getTrackDescription((error, arrlist) => { ### getTrackDescription8+ -getTrackDescription(): Promise> +getTrackDescription(): Promise> 通过Promise方式获取视频轨道信息。 @@ -1413,10 +1417,10 @@ on(type: 'startRenderFrame', callback: Callback\): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频播放首帧送显上报事件回调类型,支持的事件:'startRenderFrame'。 | -| callback | function | 是 | 视频播放首帧送显上报事件回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 视频播放首帧送显上报事件回调类型,支持的事件:'startRenderFrame'。 | +| callback | Callback\ | 是 | 视频播放首帧送显上报事件回调方法。 | **示例:** @@ -1460,10 +1464,10 @@ on(type: 'error', callback: ErrorCallback): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':视频播放中发生错误,触发该事件。 | -| callback | function | 是 | 播放错误事件回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':视频播放中发生错误,触发该事件。 | +| callback | ErrorCallback | 是 | 播放错误事件回调方法。 | **示例:** @@ -1551,7 +1555,7 @@ audioPlayer.getTrackDescription((error, arrlist) => { ## AudioRecorder -音频录制管理类,用于录制音频媒体。在调用AudioRecorder的方法前,需要先通过[createAudioRecorder()](#media.createaudiorecorder) 构建一个[AudioRecorder](#audiorecorder)实例。 +音频录制管理类,用于录制音频媒体。在调用AudioRecorder的方法前,需要先通过[createAudioRecorder()](#mediacreateaudiorecorder) 构建一个[AudioRecorder](#audiorecorder)实例。 音频录制demo可参考:[音频录制开发指导](../../media/audio-recorder.md) @@ -1794,6 +1798,7 @@ audioRecorder.prepare(); // prepare不设置参数,触发'error' | format | [AudioOutputFormat](#audiooutputformat) | 否 | 音量输出封装格式,默认设置为MPEG_4。 | | location8+ | [Location](#location8) | 否 | 音频采集的地理位置。 | | uri | string | 是 | 视频输出URI:fd://xx (fd number)
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
文件需要由调用者创建,并赋予适当的权限。 | +| audioEncoderMime | [CodecMimeType](#codecmimetype8) | 否 | 音频编码格式。 | ## AudioEncoder @@ -1827,15 +1832,17 @@ audioRecorder.prepare(); // prepare不设置参数,触发'error' ## VideoRecorder8+ -视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorder()](#media.createvideorecorder8)构建一个[VideoRecorder](#videorecorder8)实例。 +视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorder()](#mediacreatevideorecorder8)构建一个[VideoRecorder](#videorecorder8)实例。 视频录制demo可参考:[视频录制开发指导](../../media/video-recorder.md) ### 属性 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------------------ | ------------------------------------- | ---- | ---- | ---------------- | -| state8+ | [VideoRecordState](#videorecordstate) | 是 | 否 | 视频录制的状态。 | +**系统能力:** 以下各项对应的系统能力均为 SystemCapability.Multimedia.Media.VideoRecorder。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------ | -------------------------------------- | ---- | ---- | ---------------- | +| state8+ | [VideoRecordState](#videorecordstate8) | 是 | 否 | 视频录制的状态。 | ### prepare8+ @@ -1843,16 +1850,16 @@ prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; 异步方式进行视频录制的参数设置。通过注册回调函数获取返回值。 -**需要权限:** ohos.permission.MICROPHONE ohos.permission.CAMERA +**需要权限:** ohos.permission.MICROPHONE,ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| config | [VideoRecorderConfig](#videorecorderconfig) | 是 | 配置视频录制的相关参数。 | -| callback | AsyncCallback\ | 是 | 异步视频录制prepare方法的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------- | ---- | ----------------------------------- | +| config | [VideoRecorderConfig](#videorecorderconfig8) | 是 | 配置视频录制的相关参数。 | +| callback | AsyncCallback\ | 是 | 异步视频录制prepare方法的回调方法。 | **示例:** @@ -1911,15 +1918,15 @@ prepare(config: VideoRecorderConfig): Promise\; 异步方式进行视频录制的参数设置。通过Promise获取返回值。 -**需要权限:** ohos.permission.MICROPHONE ohos.permission.CAMERA +**需要权限:** ohos.permission.MICROPHONE,ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------------------- | ---- | ------------------------ | -| config | [VideoRecorderConfig](#videorecorderconfig) | 是 | 配置视频录制的相关参数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------------------------------------- | ---- | ------------------------ | +| config | [VideoRecorderConfig](#videorecorderconfig8) | 是 | 配置视频录制的相关参数。 | **返回值:** @@ -2429,14 +2436,14 @@ videoRecorder.on('error', (error) => { // 设置'error'事件回调 **系统能力:** 以下各项对应的系统能力均为 SystemCapability.Multimedia.Media.VideoRecorder。 -| 名称 | 参数类型 | 必填 | 说明 | -| --------------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| audioSourceType | [AudioSourceType](#audiosourcetype8+) | 是 | 视频录制的音频源类型。 | -| videoSourceType | [VideoSourceType](#videosourcetype8+) | 是 | 视频录制的视频源类型。 | -| profile | [VideoRecorderProfile](#videorecorderprofile8+) | 是 | 视频录制的profile。 | -| orientationHint | number | 否 | 录制视频的旋转角度。 | -| location | [Location](#location8) | 否 | 录制视频的地理位置。 | -| url | string | 是 | 视频输出URL:fd://xx (fd number)
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
文件需要由调用者创建,并赋予适当的权限。 | +| 名称 | 参数类型 | 必填 | 说明 | +| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioSourceType | [AudioSourceType](#audiosourcetype8) | 是 | 视频录制的音频源类型。 | +| videoSourceType | [VideoSourceType](#videosourcetype8) | 是 | 视频录制的视频源类型。 | +| profile | [VideoRecorderProfile](#videorecorderprofile8) | 是 | 视频录制的profile。 | +| rotation | number | 否 | 录制视频的旋转角度。 | +| location | [Location](#location8) | 否 | 录制视频的地理位置。 | +| url | string | 是 | 视频输出URL:fd://xx (fd number)
![](figures/zh-cn_image_url.png)
文件需要由调用者创建,并赋予适当的权限。 | ## AudioSourceType8+ @@ -2470,10 +2477,10 @@ videoRecorder.on('error', (error) => { // 设置'error'事件回调 | ---------------- | -------------------------------------------- | ---- | ---------------- | | audioBitrate | number | 是 | 音频编码比特率。 | | audioChannels | number | 是 | 音频采集声道数。 | -| audioCodec | [CodecMimeType](#CodecMimeType8) | 是 | 音频编码格式。 | +| audioCodec | [CodecMimeType](#codecmimetype8) | 是 | 音频编码格式。 | | audioSampleRate | number | 是 | 音频采样率。 | | fileFormat | [ContainerFormatType](#containerformattype8) | 是 | 文件的容器格式。 | -| videoCodec | [CodecMimeType](#CodecMimeType8) | 是 | 视频编码格式。 | +| videoCodec | [CodecMimeType](#codecmimetype8) | 是 | 视频编码格式。 | | videoFrameWidth | number | 是 | 录制视频帧的宽。 | | videoFrameHeight | number | 是 | 录制视频帧的高。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index 76432f944511df1b7a011ea51a36077e20ea3d8c..f225206cb25df0d6181cec7ba09fc0625c8f17b1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -1,11 +1,9 @@ -媒体库管理 -========== +# 媒体库管理 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 该组件从API Version 6开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - 导入模块 ---------- - +## 导入模块 ``` import mediaLibrary from '@ohos.multimedia.medialibrary'; ``` @@ -20,14 +18,14 @@ getMediaLibrary(context: Context): MediaLibrary **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------- | ---- | -------------------- | -| context | Context | 是 | API7以下接口可不传此参数,API 8以上接口此参数是必填参数,传入Ability实例的context,获取媒体库 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | API7以下接口可不传此参数,API 8以上接口此参数是必填参数,传入Ability实例的context,获取媒体库 | **返回值:** -| 类型 | 说明 | -| ------------ | :----- | +| 类型 | 说明 | +| ----------------------------- | :--------- | | [MediaLibrary](#medialibrary) | 媒体库实例 | **示例:** @@ -96,8 +94,8 @@ getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult> **返回值** -| 类型 | 说明 | -| ----------------------------- | -------------- | +| 类型 | 说明 | +| ------------------------------------ | -------------- | | [FetchFileResult](#fetchfileresult8) | 文件数据结果集 | **示例:** @@ -126,10 +124,10 @@ on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'| **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------- | ---- | ------------------- | -| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | callback<void> | 是 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | +| callback | callback<void> | 是 | 回调返回空 | **示例:** @@ -148,10 +146,10 @@ off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange' **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------- | ---- | ------------------- | -| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | callback<void> | 否 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | +| callback | callback<void> | 否 | 回调返回空 | **示例:** @@ -248,10 +246,10 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------- | ---- | ------------ | -| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 | -| callback |AsyncCallback<string> | 是 | callback 返回公共目录路径 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ------------------------- | +| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 | +| callback | AsyncCallback<string> | 是 | callback 返回公共目录路径 | **示例:** @@ -382,8 +380,8 @@ release(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------- | ---- | ---------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | -------------------- | | callback | AsyncCallback<void> | 是 | 回调表示成功还是失败 | **示例:** @@ -406,8 +404,8 @@ release(): Promise<void> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------------- | +| 类型 | 说明 | +| ------------------- | --------------------------------- | | Promise<void> | Promise实例,用于获取异步返回结果 | **示例:** @@ -417,11 +415,282 @@ var media = mediaLibrary.getMediaLibrary(context); media.release() ``` +### storeMediaAsset + +storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>): void + +保存媒体资源,以异步方法获取保存成功的URI,使用callback形式返回结果。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------- | ---- | ------------------------------------------- | +| option | [MediaAssetOption](#mediaassetoption) | 是 | 媒体资源选项。 | +| callback | AsyncCallback<string> | 是 | 媒体资源保存回调,返回保存成功后得到的URI。 | + +**示例:** + + ``` +let option = { + src : "file:///data/data/ohos.xxx.yyy/files/image.png", + mimeType : "image/jpeg", + relativePath : "imageDir/image2/" +}; +mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { + if (err) { + console.log("An error occurred when storing media resources."); + return; + } + console.log("Media resources stored. "); + // Obtain the URI that stores media resources. +}); + ``` + + +### storeMediaAsset + +storeMediaAsset(option: MediaAssetOption): Promise<string> + +保存媒体资源,以异步方法获取保存成功的URI,使用Promise形式返回结果。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------- | ---- | -------------- | +| option | [MediaAssetOption](#mediaassetoption) | 是 | 媒体资源选项。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ---------------------------------------------- | +| Promise<string> | Promise实例,用于异步获取保存成功后得到的URI。 | + +**示例:** + + ``` +let option = { + src : "file:///data/data/ohos.xxx.yyy/files/image.jpg", + mimeType : "image/jpeg", + relativePath : "imageDir/image2/" +}; +mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { + console.log("Media resources stored."); + // Obtain the URI that stores media resources. +}).catch((err) => { + console.log("An error occurred when storing media resources."); +}); + ``` + + +### startImagePreview + +startImagePreview(images: Array<string>, index: number, callback: AsyncCallback<void>): void + +启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(dataability://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | --------------------------------------------------- | +| images | Array<string> | 是 | 预览的图片URI("https://","dataability://")列表。 | +| index | number | 是 | 开始显示的图片序号。 | +| callback | AsyncCallback<void> | 是 | 图片预览回调,失败时返回错误信息。 | + +**示例:** + + ``` +let images = [ + "dataability:///media/external/images/media/50", + "dataability:///media/external/images/media/55" +]; +let images = [ + "https://media.xxxx.com/image1.jpg", + "https://media.xxxx.com/image2.jpg" +]; +let index = 1; +mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { + if (err) { + console.log("An error occurred when previewing the images."); + return; + } + console.log("Succeeded in previewing the images."); +}); + ``` + + +### startImagePreview + +startImagePreview(images: Array<string>, callback: AsyncCallback<void>): void + +启动图片预览界面,可以预览列表中首张本地图片(dataability://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | --------------------------------------------------- | +| images | Array<string> | 是 | 预览的图片URI("https://","dataability://")列表。 | +| callback | AsyncCallback<void> | 是 | 图片预览回调,失败时返回错误信息。 | + +**示例:** + + ``` +let images = [ + "dataability:///media/external/images/media/50", + "dataability:///media/external/images/media/55" +]; +let images = [ + "https://media.xxxx.com/image1.jpg", + "https://media.xxxx.com/image2.jpg" +]; +mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { + if (err) { + console.log("An error occurred when previewing the images."); + return; + } + console.log("Succeeded in previewing the images."); +}); + ``` + + +### startImagePreview + +startImagePreview(images: Array<string>, index?: number): Promise<void> + +启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(dataability://),也可以预览列表中的所有网络图片(https://)。使用Promise方式进行异步回调。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | --------------------------------------------------- | +| images | Array<string> | 是 | 预览的图片URI("https://","dataability://")列表。 | +| index | number | 否 | 开始显示的图片序号,不选择时默认为0。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------------------------------- | +| Promise<void> | Promise实例,用于异步获取预览结果,失败时返回错误信息。 | + +**示例:** + + ``` +let images = [ + "dataability:///media/external/images/media/50", + "dataability:///media/external/images/media/55" +]; +let images = [ + "https://media.xxxx.com/image1.jpg", + "https://media.xxxx.com/image2.jpg" +]; +let index = 1; +mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { + console.log("Succeeded in previewing the images."); +}).catch((err) => { + console.log("An error occurred when previewing the images."); +}); + ``` + + +### startMediaSelect + +startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array<string>>): void + +启动媒体选择界面,以异步方法获取选择的媒体URI列表,使用callback形式返回结果。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------------------------------- | +| option | [MediaSelectOption](#mediaselectoption) | 是 | 媒体选择选项。 | +| callback | AsyncCallback<Array<string>> | 是 | 媒体选择回调,返回选择的媒体URI(dataability://)列表。 | + +**示例:** + + ``` +let option = { + type : "image", + count : 2 +}; +mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { + if (err) { + console.log("An error occurred when selecting media resources."); + return; + } + console.log("Media resources selected."); + // Obtain the media selection value. +}); + ``` + + +### startMediaSelect + +startMediaSelect(option: MediaSelectOption): Promise<Array<string>> + +启动媒体选择界面,以异步方法获取选择的媒体URI列表,使用Promise形式返回结果。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------------------------------------- | ---- | -------------- | +| option | [MediaSelectOption](#mediaselectoption) | 是 | 媒体选择选项。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<string>> | Promise实例,用于异步获取选择的媒体URI(dataability://)列表。 | + +**示例:** + + ``` +let option = { + type : "image", + count : 2 +}; +mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { + console.log("Media resources selected."); + // Obtain the media selection value. +}).catch((err) => { + console.log("An error occurred when selecting media resources."); +}); + + ``` + ## FileAsset8+ 提供封装文件属性的方法。 -### **属性** +### 属性 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------ | ----------------------- | ---- | ---- | ------------------------------------------------------ | @@ -460,8 +729,8 @@ isDirectory(callback: AsyncCallback<boolean>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ----------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ----------------------------- | | callback | AsyncCallback<boolean> | 是 | 当前FileAsset是否是目录的回调 | **示例:** @@ -495,8 +764,8 @@ isDirectory():Promise<boolean> **返回值:** -| 类型 | 说明 | -| ---------------- | ------------------------------------------ | +| 类型 | 说明 | +| ---------------------- | ---------------------------------------- | | Promise<boolean> | Promise实例,返回当前FileAsset是否是目录 | **示例:** @@ -532,8 +801,8 @@ commitModify(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | 是 | 回调返回空 | **示例:** @@ -568,8 +837,8 @@ commitModify(): Promise<void> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| ------------------- | ------------- | | Promise<void> | Promise返回空 | **示例:** @@ -602,10 +871,10 @@ open(mode: string, callback: AsyncCallback<number>): void **参数** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | -| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) | -| callback | AsyncCallback<number> | 是 | 回调返回文件句柄 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | -------------------------------------------------------- | +| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) | +| callback | AsyncCallback<number> | 是 | 回调返回文件句柄 | **示例:** @@ -643,8 +912,8 @@ open(mode: string): Promise<number> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| --------------------- | ------------------- | | Promise<number> | Promise返回文件句柄 | **示例:** @@ -677,9 +946,9 @@ close(fd: number, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | -| fd | number | 是 | 文件描述符 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| fd | number | 是 | 文件描述符 | | callback | AsyncCallback<void> | 是 | 回调返回空 | **示例:** @@ -724,8 +993,8 @@ close(fd: number): Promise<void> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| ------------------- | ------------- | | Promise<void> | Promise返回空 | **示例:** @@ -765,8 +1034,8 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------ | | callback | AsyncCallback<image.PixelMap> | 是 | 回调返回缩略图的PixelMap | **示例:** @@ -800,9 +1069,9 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | -| size | [Size](#size8) | 是 | 缩略图尺寸 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------ | +| size | [Size](#size8) | 是 | 缩略图尺寸 | | callback | AsyncCallback<image.PixelMap> | 是 | 回调返回缩略图的PixelMap | **示例:** @@ -842,8 +1111,8 @@ getThumbnail(size?: Size): Promise<image.PixelMap> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| ----------------------------- | --------------------------- | | Promise<image.PixelMap> | Promise返回缩略图的PixelMap | **示例:** @@ -877,10 +1146,10 @@ favorite(isFavorite: boolean, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------- | ---- | -------------- | -| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ---------------------------------------------------------- | +| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | +| callback | AsyncCallback<void> | 是 | 回调返回空 | **示例:** @@ -919,8 +1188,8 @@ favorite(isFavorite: boolean): Promise<void> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| ------------------- | ------------- | | Promise<void> | Promise返回空 | **示例:** @@ -956,8 +1225,8 @@ isFavorite(callback: AsyncCallback<boolean>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ---------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ---------------------- | | callback | AsyncCallback<boolean> | 是 | 回调表示是否为收藏文件 | **示例:** @@ -995,8 +1264,8 @@ isFavorite():Promise<boolean> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| ---------------------- | ----------------------------- | | Promise<boolean> | Promise回调表示是否是收藏文件 | **示例:** @@ -1034,10 +1303,10 @@ trash(isTrash: boolean, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | -| isTrash | boolean | 是 | 是否设置为垃圾文件 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------ | +| isTrash | boolean | 是 | 是否设置为垃圾文件 | +| callback | AsyncCallback<void> | 是 | 回调返回空 | **示例:** @@ -1079,8 +1348,8 @@ trash(isTrash: boolean): Promise<void> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| ------------------- | ------------- | | Promise<void> | Promise返回空 | **示例:** @@ -1116,8 +1385,8 @@ isTrash(callback: AsyncCallback<boolean>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ------------------------------ | | callback | AsyncCallback<boolean> | 是 | 回调返回表示文件是否为垃圾文件 | **示例:** @@ -1160,8 +1429,8 @@ isTrash():Promise<boolean> **返回值:** -| 类型 | 说明 | -| ------------- | ----------------------------- | +| 类型 | 说明 | +| ------------------- | --------------------------------- | | Promise<void> | Promise回调表示文件是否为垃圾文件 | **示例:** @@ -1331,9 +1600,9 @@ getFirstObject(): Promise<FileAsset> **返回值**: -| 类型 | 说明 | -| ------------------ | -------------------------------------- | -| Promise<[FileAsset](#fileasset8)> | Promise方式返回FileAsset | +| 类型 | 说明 | +| --------------------------------------- | ------------------------ | +| Promise<[FileAsset](#fileasset8)> | Promise方式返回FileAsset | **示例**: @@ -1405,8 +1674,8 @@ async function example() { **返回值**: -| 类型 | 说明 | -| -------------------------------- | ------------------- | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | | Promise<[FileAsset](#fileasset8)> | 返回FileAsset对象 | **示例**: @@ -1473,8 +1742,8 @@ getLastObject(): Promise<FileAsset> **返回值**: -| 类型 | 说明 | -| -------------------------------- | ------------------- | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | | Promise<[FileAsset](#fileasset8)> | 返回FileAsset对象 | **示例**: @@ -1542,14 +1811,14 @@ getPositionObject(index: number): Promise<FileAsset> **参数**: -| 参数 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | -------------------- | +| 参数 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | --------------------------- | | index | number | 是 | 要获取的文件的索引,从0开始 | **返回值**: -| 类型 | 说明 | -| -------------------------------- | ------------------- | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | | Promise<[FileAsset](#fileasset8)> | 返回FileAsset对象 | **示例**: @@ -1648,6 +1917,8 @@ async function example() { ### **属性** +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + | 名称 | 参数型 | 可读 | 可写 | 说明 | | ------------ | ------ | ---- | ---- | -------------- | | albumId | number | 是 | 否 | 相册编号 | @@ -1670,9 +1941,9 @@ commitModify(callback: AsyncCallback<void>): void **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | ------------------- | ---- | ----------------------------- | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | 是 | 回调返回空 | **示例**: @@ -1707,8 +1978,8 @@ commitModify(): Promise<void> **返回值**: -| 类型 | 说明 | -| ------------- | ---------------------------------------------------- | +| 类型 | 说明 | +| ------------------- | ----------------- | | Promise<void> | Promise调用返回空 | **示例**: @@ -1742,9 +2013,9 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileRe **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------------- | ---- | --------------------------------- | -| options | [MediaFetchOptions](#mediafetchoptions8) | 是 | 媒体检索选项 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | --------------------------------- | +| options | [MediaFetchOptions](#mediafetchoptions8) | 是 | 媒体检索选项 | | callback | AsyncCallback<[FetchFileResult](#fetchfileresult8)> | 是 | 异步返回FetchFileResult之后的回调 | **示例**: @@ -1808,6 +2079,8 @@ async function example() { 注册设备的信息。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------- | ---------- | ---- | ---- | ---------------- | | deviceName | string | 是 | 否 | 注册设备的名称 | @@ -1822,6 +2095,8 @@ MediaType 枚举,媒体类型。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + | 名称 | 默认值 | 描述 | | ----- | ------ | ---- | | FILE | 0 | 文件 | @@ -1834,6 +2109,8 @@ FileKey 枚举,文件关键信息。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + | 名称 | 默认值 | 描述 | | ------------- | ------------------- | ---------------------------------------------------------- | | ID | file_id | 文件编号 | @@ -1861,6 +2138,8 @@ DirectoryType 枚举,目录类型。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + | 名称 | 默认值 | 描述 | | ------------- | ------ | ------------------ | | DIR_CAMERA | 0 | 表示Camera文件路径 | @@ -1875,6 +2154,8 @@ DeviceType 枚举,设备类型。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + | 名称 | 默认值 | 描述 | | ------------ | ------ | ---------- | | TYPE_UNKNOWN | 0 | 未识别设备 | @@ -1889,14 +2170,16 @@ DeviceType 检索条件。 -| 名称 | 类型 | 可读 | 可写 | 必填 |说明 | -| ------------- | ------------- | ---- | ---- | ---- |---------------- | -| selections | string | 是 | 是 |是 | 检索条件,使用[FileKey](#filekey)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?‘, | -| selectionArgs | Array<string> | 是 | 是 |是 | 检索条件的值,对应selections中检索条件列的值。
示例:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order | string | 是 | 是 | 否 |检索结果排序方式,使用[FileKey](#filekey)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:
升序排列:order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
降序排列:order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | -| uri | string | 是 | 是 | 否 |文件URI | -| networkId | string | 是 | 是 | 否 |注册设备网络ID | -| extendArgs | string | 是 | 是 | 否 |扩展的检索参数,目前没有扩展检索参数 | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + +| 名称 | 类型 | 可读 | 可写 | 必填 | 说明 | +| ------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| selections | string | 是 | 是 | 是 | 检索条件,使用[FileKey](#filekey)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?‘, | +| selectionArgs | Array<string> | 是 | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。
示例:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | +| order | string | 是 | 是 | 否 | 检索结果排序方式,使用[FileKey](#filekey)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:
升序排列:order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
降序排列:order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | +| uri | string | 是 | 是 | 否 | 文件URI | +| networkId | string | 是 | 是 | 否 | 注册设备网络ID | +| extendArgs | string | 是 | 是 | 否 | 扩展的检索参数,目前没有扩展检索参数 | ## Size8+ @@ -1907,3 +2190,30 @@ DeviceType | width | number | 是 | 是 | 宽(单位:像素) | | height | number | 是 | 是 | 高(单位:像素) | +## MediaAssetOption + +媒体资源选项。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ------ | ---- | ------------------------------------------------------------ | +| src | string | 是 | 媒体库数据的URI。 | +| mimeType | string | 是 | 媒体MIME(Multipurpose Internet Mail Extensions)类型。
例:'image/\*'、'video/\*'等。 | +| relativePath | string | 否 | 自定义媒体资源保存位置,不填则保存到默认路径。例:imageDir/image2/(媒体资源将保存位置为:default/imageDir/image2/),default为默认保存路径。 | + +## MediaSelectOption + +媒体资源类型选项。 + +本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core + +| 名称 | 类型 | 必填 | 描述 | +| ----- | ------ | ---- | ------------------------------ | +| type | string | 是 | 媒体类型,包括:image,video。 | +| count | number | 是 | 媒体选择最大数量。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md index 44ce21f9db6b77f0fab9179db7c21be38a40e7da..8b706d69a8d9cfac50036e6bc71fc6a0951c2e04 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -416,7 +416,7 @@ plainArray.clear(); ### forEach -forEach(callbackfn: (value: T, key?: number, PlainArray?: PlainArray) => void, thisArg?: Object): void +forEach(callbackfn: (value?: T, index?: number, PlainArray?: PlainArray) => void, thisArg?: Object): void 通过回调函数来遍历实例对象上的元素以及元素对应的下标。 @@ -431,8 +431,8 @@ callbackfn的参数说明: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | value | T | 是 | 当前遍历到的元素键值对的值。 | -| key | number | 是 | 当前遍历到的元素键值对的键。 | -| plainArray | PlainArray | 否 | 当前调用forEach方法的实例对象。 | +| index | number | 是 | 当前遍历到的元素键值对的键。 | +| plainArray | PlainArray | 否 | 当前调用forEach方法的实例对象。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-process.md b/zh-cn/application-dev/reference/apis/js-apis-process.md index 14879cd9d6a3d8d548dc4e88b5e33392d60c4799..e255e9ab3b02e7c1abfb8b72112ebce227d06f9e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-process.md +++ b/zh-cn/application-dev/reference/apis/js-apis-process.md @@ -262,7 +262,7 @@ var pres = process.getThreadPriority(tid); ## process.getStartRealtime8+ -getStartRealtime() :number +getStartRealtime(): number 获取从系统启动到进程启动所经过的实时时间(以毫秒为单位)。 @@ -280,7 +280,7 @@ var realtime = process.getStartRealtime(); ## process.getPastCputime8+ -getPastCputime() :number +getPastCputime(): number 获取进程启动到当前时间的CPU时间(以毫秒为单位)。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md index ae3745ac1dc61f5671c14d3546c7783257f2fa33..ac3cf96b369ecc02ae6ebc10cf9687f37a6de8ad 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,7 +1,7 @@ # 资源管理 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -766,7 +766,7 @@ closeRawFileDescriptor(path: string): Promise<void> }); ``` -### release +### release7+ release(); diff --git a/zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md b/zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md index b0eb0fbaf3c5f628c3621dfd62b78af9f2f2eee8..ed954168db6cdeb5fc250e12aafccc2a49e125a9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @@ -126,7 +126,7 @@ getFreeSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):vo }); ``` -## storagestatistics.getBundleStats9+ +## storagestatistics.getBundleStats getBundleStats(packageName: string): Promise<BundleStats> @@ -157,7 +157,7 @@ getBundleStats(packageName: string): Promise<BundleStats> }); ``` -## storagestatistics.getBundleStats9+ +## storagestatistics.getBundleStats getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>): void diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md index 498ba951ea8b663862f0535392956fa8f02364db..cfa19710dfbd77dd6840c00902c3543965acdd8e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @@ -15,17 +15,6 @@ import sensor from '@system.sensor'; ``` -## 权限列表 - -计步器:ohos.permission.ACTIVITY_MOTION - -心率:ohos.permission.READ_HEALTH_DATA - -加速度:ohos.permission.ACCELEROMETER - -陀螺仪:ohos.permission.GYROSCOPE - - ## 传感器错误码列表 | 错误码 | 说明 | @@ -38,6 +27,10 @@ subscribeAccelerometer(Object): void 观察加速度数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.ACCELEROMETER,该权限为系统权限 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -79,6 +72,10 @@ unsubscribeAccelerometer(): void 取消订阅加速度数据。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.ACCELEROMETER,该权限为系统权限 + **示例:** ``` @@ -91,6 +88,8 @@ subscribeCompass(Object): void 订阅罗盘数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -126,6 +125,8 @@ unsubscribeCompass(): void 取消订阅罗盘。 +**系统能力**:SystemCapability.Sensors.Sensor + **示例:** ``` @@ -138,6 +139,8 @@ subscribeProximity(Object): void 订阅距离感应数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -173,6 +176,8 @@ unsubscribeProximity(): void 取消订阅距离感应。 +**系统能力**:SystemCapability.Sensors.Sensor + **示例:** ``` @@ -185,6 +190,8 @@ sensor.subscribeLight(Object): void 订阅环境光线感应数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -220,6 +227,8 @@ unsubscribeLight(): void 取消订阅环境光线感应。 +**系统能力**:SystemCapability.Sensors.Sensor + **示例:** ``` @@ -232,6 +241,10 @@ subscribeStepCounter(Object): void 订阅计步传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.ACTIVITY_MOTION + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -267,6 +280,10 @@ unsubscribeStepCounter(): void 取消订阅计步传感器。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.ACTIVITY_MOTION + **示例:** ``` @@ -280,6 +297,8 @@ subcribeBarometer(Object): void 订阅气压传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -316,6 +335,8 @@ unsubscribeBarometer(): void 取消订阅气压传感器。 +**系统能力**:SystemCapability.Sensors.Sensor + **示例:** ``` @@ -329,6 +350,10 @@ subscribeHeartRate(Object): void 订阅心率传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.READ_HEALTH_DATA + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -365,6 +390,10 @@ unsubscribeHeartRate(): void 取消订阅心率。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.READ_HEALTH_DATA + **示例:** ``` @@ -377,6 +406,8 @@ subscribeOnBodyState(Object): void 订阅设备佩戴状态。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。 +**系统能力**:SystemCapability.Sensors.Sensor + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -412,6 +443,8 @@ unsubscribeOnBodyState(): void 取消订阅设备佩戴状态。 +**系统能力**:SystemCapability.Sensors.Sensor + **示例:** ``` @@ -424,6 +457,8 @@ getOnBodyState(Object): void 获取设备佩戴状态。 +**系统能力**:SystemCapability.Sensors.Sensor + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -459,6 +494,8 @@ subscribeDeviceOrientation(interval: string, success: (data: DeviceOrientationRe 针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效;针对同一个方法内,不支持多次调用。 +**系统能力**:SystemCapability.Sensors.Sensor + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -499,6 +536,8 @@ unsubscribeDeviceOrientation(): void 取消订阅设备方向传感器数据。 +**系统能力**:SystemCapability.Sensors.Sensor + **示例:** ``` @@ -513,6 +552,10 @@ subscribeGyroscope(interval: string, success: (data: GyroscopeResponse), fail?: 针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效;针对同一个方法内,不支持多次调用。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.GYROSCOPE,该权限为系统权限 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -554,6 +597,10 @@ unsubscribeGyroscope(): void 取消订阅陀螺仪数据。 +**系统能力**:SystemCapability.Sensors.Sensor + +**需要权限**:ohos.permission.GYROSCOPE,该权限为系统权限 + **示例:** ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md b/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md index b30152d767b1b7216700bd3f11a4811500307512..67ab27690a460b15d277385af4259e01a86dbd13 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @@ -21,6 +21,10 @@ vibrate(Object): void 触发设备振动。 +**系统能力**:SystemCapability.Sensors.MiscDevice + +**需要权限**:ohos.permission.VIBRATE,该权限为系统权限 + **参数:** | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-uitest.md b/zh-cn/application-dev/reference/apis/js-apis-uitest.md new file mode 100644 index 0000000000000000000000000000000000000000..6f2122ff96507d4a1f3992d3d802b70886d33292 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-uitest.md @@ -0,0 +1,943 @@ +# UiTest + +>**说明:** +> +>本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {UiDriver,BY,MatchPattern} from '@ohos.uitest' +``` + +## By + +UiTest框架通过By类提供了丰富的控件特征描述API,用以进行控件筛选来匹配/查找出目标控件。 +By提供的API能力具有以下几个特点: + 1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id + 2、控件属性支持多种匹配模式 + 3、支持控件绝对定位,相对定位,可通过isBefore和isAfter等API限定邻近控件特征进行辅助定位 +By类提供的所有API均为同步接口,建议使用者通过静态构造器BY来链式创建By对象,例如:BY.text('123').type('button') + +### enum MatchPattern + +控件属性支持的匹配模式 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Test.UiTest + +| 名称 | 值 | 说明 | +| ----------- | ---- | ------------ | +| EQUALS | 0 | 等于给定值 | +| CONTAINS | 1 | 包含给定值 | +| STARTS_WITH | 2 | 以给定值开始 | +| ENDS_WITH | 3 | 以给定值结束 | + +### By.text + +text(txt:string,pattern?:MatchPattern):By + +指定目标控件文本属性,支持多种匹配模式,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ---------------------------------- | +| txt | string | 是 | 指定控件文本,用于匹配目标控件文本 | +| pattern | MatchPattern | 否 | 指定的文本匹配模式,默认为EQUALS | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.text('123') //使用静态构造器BY创建by对象,指定目标控件的text属性 +``` + + +### By.key + +key(key:string):By; + +指定目标控件key值属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | --------------- | +| key | string | 是 | 指定控件的Key值 | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.key('123') //使用静态构造器BY创建by对象,指定目标控件的key值属性 +``` + + +### By.id + +id(id:number):By; + +指定目标控件id属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------ | +| id | number | 是 | 指定控件id值 | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.id(123) //使用静态构造器BY创建by对象,指定目标控件的id属性 +``` + + +### By.type + +type(tp:string):By; + +指定目标控件的控件类型属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------ | +| tp | string | 是 | 指定控件类型 | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.type('button') //使用静态构造器BY创建by对象,指定目标控件的控件类型属性 +``` + + +### By.clickable + +clickable(b?:bool):By; + +指定目标控件的可点击状态属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | 否 | 指定控件可点击状态,默认为true | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.clickable(true) //使用静态构造器BY创建by对象,指定目标控件的可点击状态属性 +``` + + +### By.scrollable + +scrollable(b?:bool):By; + +指定目标控件的可滑动状态属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------------------- | +| b | bool | 否 | 控件可滑动状态,默认为true | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.scrollable(true) //使用静态构造器BY创建by对象,指定目标控件的可滑动状态属性 +``` + +### By.enabled + +enabled(b?:bool):By; + +指定目标控件的使能状态属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ---------------------------- | +| b | bool | 否 | 指定控件使能状态,默认为true | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.enabled(true) //使用静态构造器BY创建by对象,指定目标控件的使能状态属性 +``` + +### By.focused + +focused(b?:bool):By; + +指定目标控件的获焦状态属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------------------ | +| b | bool | 否 | 控件获焦状态,默认为true | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.focused(true) //使用静态构造器BY创建by对象,指定目标控件的获焦状态属性 +``` + +### By.selected + +selected(b?:bool):By; + +指定目标控件的被选中状态属性,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | 否 | 指定控件被选中状态,默认为true | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.selected(true) //使用静态构造器BY创建by对象,指定目标控件的被选中状态属性 +``` + +### By.isBefore + +isBefore(by:By):By; + +指定目标控件位于给出的特征属性控件之前,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------- | +| by | By | 是 | 特征控件的属性 | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.isBefore(by.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之前 +``` + +### By.isAfter + +isAfter(by:By):By; + +指定目标控件位于给出的特征属性控件之后,返回By对象自身。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------- | +| by | By | 是 | 特征控件的属性 | + +**返回值:** + +| 类型 | 说明 | +| ---- | -------------- | +| By | 返回By对象自身 | + +**示例:** + +``` +let by = BY.isAfter(by.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之后 +``` + +## UiComponent + +UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属性获取,控件点击,滑动查找,文本注入等API。 +该类提供的所有方法都使用Promise方式作为异步方法,需使用await调用。 + +### UiComponent.click + +click():Promise; + +控件对象进行点击操作。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +``` +await button.click() +``` + +### UiComponent.doubleClick + +doubleClick():Promise; + +控件对象进行双击操作。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +``` +await buttont.doubleClick() +``` + +### UiComponent.longClick + +longClick():Promise; + +控件对象进行长按操作。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +``` +await button.longClick() +``` + +### UiComponent.getId + +getId():Promise; + +获取控件对象的id值。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------- | +| Promise; | 以Promise形式返回控件id值 | + +**示例:** + +``` +let num = await button.getId() +``` + +### UiComponent.getKey + +getKey():Promise; + +获取控件对象的key值。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------------- | +| Promise; | 以Promise形式返回控件key值 | + +**示例:** + +``` +let str_key = await button.getKey() +``` + +### UiComponent.getText + +getText():Promise; + +获取控件对象的文本信息。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------- | +| Promise; | 以Promise形式返回控件的文本信息 | + +**示例:** + +``` +let text = await button.getText() +``` + +### UiComponent.getType + +getType():Promise; + +获取控件对象的控件类型。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------- | +| Promise; | 以Promise形式返回控件对象的类型 | + +**示例:** + +``` +let type =await button.getType() +``` + +### UiComponent.isClickable + +isClickable():Promise; + +获取控件对象可点击状态。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------------- | +| Promise; | 以Promise形式返回控件对象可点击状态 | + +**示例:** + +``` +if(await button.isClickable()) + console.info('This button can be Clicked') +else + console.info('This button can not be Clicked') + +``` + +### UiComponent.isScrollable + +isScrollable():Promise; + +获取控件对象可滑动状态。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------------- | +| Promise; | 以Promise形式返回控件对象可滑动状态 | + +**示例:** + +``` +if(await scrollBar.isScrollable()) + console.info('This scrollBar can be operated') +else + console.info('This scrollBar can not be operated') +``` + + +### UiComponent.isEnabled + +isEnabled():Promise; + +获取控件使能状态。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise; | 以Promise形式返回控件使能状态 | + +**示例:** + +``` +if(await button.isEnabled()) + console.info('This button can be operated') +else + console.info('This button can not be operated') +``` + +### UiComponent.isFocused + +isFocused():Promise; + +判断控件对象是否获焦。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| -------------- | --------------------------------- | +| Promise; | 以Promise形式返回控件对象是否获焦 | + +**示例:** + +``` +if(await button.isFocused()) + console.info('This button is focused') +else + console.info('This button is not focused') +``` + +### UiComponent.isSelected + +isSelected():Promise; + +获取控件对象被选中状态。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------------- | +| Promise; | 以Promise形式返回控件对象被选中状态 | + +**示例:** + +``` +if(await button.isSelected()) + console.info('This button is selected') +else + console.info('This button is not selected') +``` + +### UiComponent.inputText + +inputText(text: string):Promise; + +向控件中输入文本(适用于文本框控件)。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------- | +| text | string | 是 | 用于向控件输入的文本信息, | + +**示例:** + +``` +await button.inputText('next page') +``` + +### UiComponent.scrollSearch + +scrollSearch(by:By):Promise; + +在控件上滑动查找目标控件(适用于List等控件)。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------------- | +| by | By | 是 | 目标控件的体属性要求 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ----------------------------------- | +| Promise; | 以Promise形式返回找到的目标控件对象 | + +**示例:** + +``` +let button = await scrollBar.scrollSearch(By.text('next page')) +``` + +## UiDriver + +UiDriver类为uitest测试框架的总入口,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等API。 +该类提供的方法除UiDriver.create()以外的所有方法都使用Promise方式作为异步方法,需使用await调用。 + +### UiDriver.create + +static create():UiDriver; + +静态方法,构造一个UiDriver对象,并返回该对象。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**返回值:** + +| 类型 | 说明 | +| ------- | ---------------------- | +| UiDrive | 返回构造的UiDriver对象 | + +**示例:** + +``` +let driver = UiDriver.create() +``` + +### UiDriver.delayMs + +delayMs(duration:number):Promise; + +UiDriver对象在给定的时间内延时。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ---------- | +| duration | number | 是 | 给定的时间 | + +**示例:** + +``` +await UiDriver.delayMs(1000) +``` + +### UiDriver.findComponent + +findComponent(by:By):Promise; + +在UiDriver对象中,根据给出的目标控件属性要求查找目标控件。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------------ | +| by | By | 是 | 目标控件的属性要求 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise; | 以Promise形式返回找到的控件对象 | + +**示例:** + +``` +let button = await UiDriver.findComponent(By.text('next page')) +``` + +### UiDriver.findComponents + +findComponents(by:By):Promise>; + +在UiDriver对象中,根据给出的目标控件属性要求查找出所有匹配控件,以列表保存。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------------ | +| by | By | 是 | 目标控件的属性要求 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------- | ------------------------------------- | +| Promise>; | 以Promise形式返回找到的控件对象的列表 | + +**示例:** + +``` +let > = await UiDriver.findComponents(By.text('next page')) +``` + +### UiDriver.assertComponentExist + +assertComponentExist(by:By):Promise; + +断言API,用于断言当前界面存在满足给出的目标控件属性的控件; 如果控件不存在,该API将抛出JS异常,使当前测试用例失败。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------------ | +| by | By | 是 | 目标控件的属性要求 | + +**示例:** + +``` +await assertComponentExist(By.text('next page')) +``` + +### UiDriver.pressBack + +pressBack():Promise; + +UiDriver对象进行点击BACK键的操作。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**示例:** + +``` +UiDriver.pressBack() +``` + +### UiDriver.triggerKey + +triggerKey(keyCode:number):Promise; + +UiDriver对象采取如下操作:通过key值找到对应键并点击。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | --------- | +| keyCode | number | 是 | 指定key值 | + +**示例:** + +``` +await UiDriver.triggerKey(123) +``` + +### UiDriver.click + +click(x:number,y:number):Promise; + +UiDriver对象采取如下操作:在目标坐标点单击。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | 是 | 以(number,number)的形式传入特定点的坐标信息 | + +**示例:** + +``` +await UiDriver.click(100,100) +``` + +### UiDriver.doubleClick + +doubleClick(x:number,y:number):Promise; + +UiDriver对象采取如下操作:在目标坐标点双击。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | 是 | 以(number,number)的形式传入特定点的坐标信息 | + +**示例:** + +``` +await UiDriver.doubleClick(100,100) +``` + +### UiDriver.longClick + +longClick(x:number,y:number):Promise; + +UiDriver对象采取如下操作:在目标坐标点长按下鼠标左键。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | 是 | 以(number,number)的形式传入特定点的坐标信息 | + +**示例:** + +``` +await UiDriver.longClick(100,100) +``` + +### UiDriver.swipe + +swipe(startx:number,starty:number,endx:number,endy:number):Promise; + +UiDriver对象采取如下操作:从给出的起始坐标点滑向给出的目的坐标点。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | ------------- | ---- | ------------------------------------------- | +| startx,starty | number,number | 是 | 以(number,number)的形式传入起始点的坐标信息 | +| endx,endy | number,number | 是 | 以(number,number)的形式传入目的点的坐标信息 | + +**示例:** + +``` +await UiDriver.swipe(100,100,200,200) +``` + +### UiDriver.screenCap + +screenCap(savePath:string):Promise; + +UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的图片至给出的保存路径中。 + +**需要权限**:NA + +**系统能力**:SystemCapability.Test.UiTest + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------ | +| savePath | string | 是 | 文件保存路径 | + +**示例:** + +``` +await UiDriver.screenCap('/local/tmp/') +``` + diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index 759d5e288360d4cb2ffb9b43e3b6dc17d2c7d441..f3aa4f637a092ae84f4c114a368be2e1a7f5d093 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -174,7 +174,7 @@ TextDecoder的构造函数。 ### decode -decode(input: Unit8Array, options?:{stream?:false}):string +decode(input: Unit8Array, options?:{stream?:false}): string 通过输入参数解码后输出对应文本。 @@ -2321,7 +2321,7 @@ isStringObject(value: Object):boolean ### isSymbolObjec8+ -isSymbolObjec(value: Object):boolean +isSymbolObjec(value: Object): boolean 检查输入的value是否是Symbol对象类型。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-vector.md b/zh-cn/application-dev/reference/apis/js-apis-vector.md index 3e2718716cfadfb879206520f3e226a64ee35774..23351ac3b6c21bd45cb5b5b90acc826791ae9635 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vector.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vector.md @@ -569,6 +569,7 @@ let result = vector.toSting(); ### copyToArray copyToArray(array: Array<T>): void + 将Vector实例中的元素按照下标复制到指定数组。 **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-volumemanager.md b/zh-cn/application-dev/reference/apis/js-apis-volumemanager.md index 55913343e0462c816c5592d07d09cc5b5d78cff5..c644344a1efaacae2939a6828fa27714b1a56c1a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-volumemanager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-volumemanager.md @@ -11,7 +11,7 @@ import volumemanager from "@ohos.volumeManager"; ``` -## volumemanager.getAllVolumes +## volumemanager.getAllVolumes9+ getAllVolumes(): Promise<Array<Volume>> @@ -33,7 +33,7 @@ getAllVolumes(): Promise<Array<Volume>> }); ``` -## volumemanager.getAllVolumes +## volumemanager.getAllVolumes9+ getAllVolumes(callback: AsyncCallback<Array<Volume>>): void diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-web.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-web.md index a3f596d3f587e84039f06e97378a80525155032e..e74ae199ab7940c8e09e9631c2692b6f80348971 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-web.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-web.md @@ -3,11 +3,8 @@ >![](../../public_sys-resources/icon-note.gif) **说明:** > 该组件从API version 6开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -## 权限列表 -ohos.permission.INTERNET - ## 约束 -web组件不跟随转场动画。一个页面仅支持一个web组件。不支持预览。 +web组件不跟随转场动画。一个页面仅支持一个web组件。 ## 子组件 不支持。 diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index cfd6f34071a5c5a828d3c26f2f358292132103f1..0165dc8046718a4a63f1b9d20c75f0f5cef89151 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -55,8 +55,10 @@ - [DataPanel](ts-basic-components-datapanel.md) - [DatePicker](ts-basic-components-datepicker.md) - [Divider](ts-basic-components-divider.md) + - [Gauge](ts-basic-components-gauge.md) - [Image](ts-basic-components-image.md) - [ImageAnimator](ts-basic-components-imageanimator.md) + - [Marquee](ts-basic-components-marquee.md) - [LoadingProgress](ts-basic-components-loadingprogress.md) - [Progress](ts-basic-components-progress.md) - [QRCode](ts-basic-components-qrcode.md) @@ -75,6 +77,7 @@ - [TextClock](ts-basic-components-textclock.md) - [Web](ts-basic-components-web.md) - [Xcomponent](ts-basic-components-xcomponent.md) + - [PluginComponent](ts-basic-components-plugincomponent.md) - 容器组件 - [AlphabetIndexer](ts-container-alphabet-indexer.md) - [Badge](ts-container-badge.md) @@ -100,6 +103,8 @@ - [Tabs](ts-container-tabs.md) - [TabContent](ts-container-tabcontent.md) - [Refresh](ts-container-refresh.md) + - [Stepper](ts-basic-components-stepper.md) + - [StepperItem](ts-basic-components-stepperitem.md) - 媒体组件 - [Video](ts-media-components-video.md) - 绘制组件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-animation.md index bf1021189ad456a896e297ecd0fb4db7a475dfff..7fd62a4d2ac2a86933d2a0fc772bc73e01e1babc 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-animation.md @@ -1,13 +1,10 @@ # 动画 - -- **[属性动画](ts-animatorproperty.md)** - -- **[显式动画](ts-explicit-animation.md)** - -- **[转场动画](ts-transition-animation.md)** - -- **[路径动画](ts-motion-path-animation.md)** - -- **[矩阵变换](ts-matrix-transformation.md)** - -- **[插值计算](ts-interpolation-calculation.md)** \ No newline at end of file + - [属性动画](ts-animatorproperty.md) + - [显式动画](ts-explicit-animation.md) + - 转场动画 + - [页面间转场](ts-page-transition-animation.md) + - [组件内转场](ts-transition-animation-component.md) + - [共享元素转场](ts-transition-animation-shared-elements.md) + - [路径动画](ts-motion-path-animation.md) + - [矩阵变换](ts-matrix-transformation.md) + - [插值计算](ts-interpolation-calculation.md) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md index 613eba133009657e012281660d9021e60cf9c41d..8de0f521c69a603c96b6a3c3f50591dac5aea3c1 100755 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -5,12 +5,6 @@ 提供具有网页显示能力的Web组件。 -## 权限列表 - -ohos.permission.INTERNET - -ohos.permission.READ_USER_STORAGE - ## 子组件 无 @@ -37,9 +31,9 @@ ohos.permission.READ_USER_STORAGE | 名称 | 参数类型 | 默认值 | 描述 | | ----------------- | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ | | domStorageAccess | boolean | false | 设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启。 | -| fileAccess | boolean | true | 设置是否开启通过$rawfile(filepath/filename)访问应用中rawfile路径的文件, 默认启用。 | +| fileAccess | boolean | true | 设置是否开启通过[$rawfile(filepath/filename)](../../ui/ts-application-resource-access.md#资源引用)访问应用中rawfile路径的文件, 默认启用。 | | imageAccess | boolean | true | 设置是否允许自动加载图片资源,默认允许。 | -| javaScriptProxy | {
object: object,
name: string,
methodList: Array\,
controller: WebController
} | - | 注入JavaScript对象到window对象中,并在window对象中调用该对象及其方法。所有参数不支持更新。
object: 参与注册的对象。只能声明方法,不能声明属性
name: 参与注册对象的名称,与JS中调用的对象名一致。
methodList: 参与注册的对象中的方法列表。
controller: 控制器。 | +| javaScriptProxy | {
object: object,
name: string,
methodList: Array\,
controller: WebController
} | - | 注入JavaScript对象到window对象中,并在window对象中调用该对象的方法。所有参数不支持更新。
object: 参与注册的对象。只能声明方法,不能声明属性 。其中方法的参数和返回类型只能为string,number,boolean。
name: 注册对象的名称,与window中调用的对象名一致。注册后window对象可以通过此名字访问应用侧JavaScript对象。
methodList: 参与注册的应用侧JavaScript对象的方法。
controller: 控制器。 | | javaScriptAccess | boolean | true | 设置是否允许执行JavaScript脚本,默认允许执行。 | | mixedMode | [MixedMode](#MixedMode) | MixedMode.None | 设置是否允许加载超文本传输协议(HTTP)和超文本传输安全协议(HTTPS)混合内容,默认不允许加载HTTP和HTTPS混合内容。 | | onlineImageAccess | boolean | true | 设置是否允许从网络加载图片资源(通过HTTP和HTTPS访问的资源),默认允许访问。 | @@ -50,40 +44,40 @@ ohos.permission.READ_USER_STORAGE > 通用属性仅支持[width](ts-universal-attributes-size.md#属性)、[height](ts-universal-attributes-size.md#属性)、[padding](ts-universal-attributes-size.md#属性)、[margin](ts-universal-attributes-size.md#属性)、[border](ts-universal-attributes-border.md#属性)。 - MixedMode枚举说明 - | 名称 | 描述 | - | ---------- | ------------------------------------------------------------ | - | All | 允许加载HTTP和HTTPS混合内容。 | - | Compatible | 混合内容兼容性模式,一些不安全的内容可能被安全来源加载,其他类型的内容将被阻止。 | - | None | HTTP和HTTPS混合内容,不加载HTTP的资源。 | + | 名称 | 描述 | + | ---------- | ----------------------------------------------------------- | + | All | 允许加载HTTP和HTTPS混合内容。所有不安全的内容都可以被加载。 | + | Compatible | 混合内容兼容性模式,部分不安全的内容可能被加载。 | + | None | 不允许加载HTTP和HTTPS混合内容。 | ## 事件 -通用事件仅支持[onFocus](ts-universal-focus-event.md#事件)。 +不支持通用事件。 | 名称 | 功能描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onAlert(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) |

网页触发alert()告警弹窗时触发。
url:当前显示的对话框所在的网页。
message:对话框中显示的信息。
JsResult:根据用户的操作确认或取消对话框。

| -| onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) |

即将离开当前页面(刷新或关闭)时触发。
url:Web组件返回的下载URL。
message:Web组件返回的信息。
JsResult:Web组件返回的弹窗确认或弹窗取消功能对象。

| -| onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) |

网页触发confirm()确认弹窗时触发。
url:Web组件返回的下载URL。
message:Web组件返回的信息。
JsResult:Web组件返回的弹窗确认或弹窗取消功能对象。

| -| onConsole(callback: (event?: { message: ConsoleMessage }) => boolean) |

向主应用报告JavaScript控制台消息时触发该回调。
message:触发的控制台信息。

| -| onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) |

下载开始时触发该回调。
url:Web组件返回的下载URL。
userAgent:Web组件返回的用户代理名称。
contentDisposition:Web组件返回的响应头。
mimetype:Web组件返回的媒体类型(MIME)信息。
contentLength:Web组件返回的内容长度。

| -| onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void) |

网页加载错误时触发该回调。
request:网页的请求信息。
error:网页的错误信息 。

| -| onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: WebResourceResponse }) => void) |

网页加载出现网络错误时触发该回调。
request:网页的请求信息。
response:网页的响应信息

| -| onPageBegin(callback: (event?: { url: string }) => void) |

网页加载时触发该回调。
url:Web组件返回的URL。

| -| onPageEnd(callback: (event?: { url: string }) => void) |

网页加载结束时触发该回调。
url:Web组件返回的URL。

| -| onProgressChange(callback: (event?: { newProgress: number }) => void) |

网页加载进度变化时触发该回调。
newProgress:加载进度,取值范围为0到100的整数。

| -| onTitleReceive(callback: (event?: { title: string }) => void) |

网页主页面标题更改时触发该回调。
title:标题内容。

| +| onAlert(callback: (event?: { url: string; message: string; result: [JsResult](#JsResult对象说明) }) => boolean) |

网页触发alert()告警弹窗时触发回调。
当回调返回false时,触发默认弹窗。当回调返回true时,系统应用可以调用系统弹窗能力(只有确认场景),并且根据用户的确认操作调用JsResult通知web组件。
url:当前显示弹窗所在网页的URL。
message:弹窗中显示的信息。
JsResult:通知web组件用户操作行为。

| +| onBeforeUnload(callback: (event?: { url: string; message: string; result: [JsResult](#JsResult对象说明) }) => boolean) |

刷新或关闭场景下,在即将离开当前页面时触发此回调。
当回调返回false时,触发默认弹窗。当回调返回true时,系统应用可以调用系统弹窗能力(包括确认和取消),并且需要根据用户的确认或取消操作调用JsResult通知web组件最终是否离开当前页面。
url:当前显示弹窗所在网页的URL。
message:弹窗中显示的信息。
JsResult:通知web组件用户操作行为。

| +| onConfirm(callback: (event?: { url: string; message: string; result: [JsResult](#JsResult对象说明) }) => boolean) |

网页调用confirm()告警时触发此回调。
当回调返回false时,触发默认弹窗。当回调返回true时,系统应用可以调用系统弹窗能力(包括确认和取消),并且需要根据用户的确认或取消操作调用JsResult通知web组件。
url:当前显示弹窗所在网页的URL。
message:弹窗中显示的信息。
JsResult:通知web组件用户操作行为。

| +| onConsole(callback: (event?: { message: [ConsoleMessage](#ConsoleMessage对象说明) }) => boolean) |

通知宿主应用JavaScript console消息。
message:触发的控制台信息。

| +| onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) |

网页的下载任务开始时触发该回调。
url:文件下载的URL。
userAgent:下载的用户代理(UA)名称。
contentDisposition:服务器返回的 Content-Disposition响应头,可能为空。
mimetype:服务器返回内容媒体类型(MIME)信息。
contentLength:服务器返回文件的长度。

| +| onErrorReceive(callback: (event?: { request: [WebResourceRequest](#WebResourceError对象说明), error: [WebResourceError](#WebResourceError对象说明) }) => void) |

网页加载遇到错误时触发该回调。
出于性能考虑,建议此回调中尽量执行简单逻辑。
request:网页请求的封装信息。
error:网页加载资源错误的封装信息 。

| +| onHttpErrorReceive(callback: (event?: { request: [WebResourceRequest](#WebResourceError对象说明), response: [WebResourceResponse](#WebResourceResponse对象说明) }) => void) |

网页加载资源遇到的HTTP错误(响应码>=400)时触发该回调。
request:网页请求的封装信息。
response:网页响应的封装信息

| +| onPageBegin(callback: (event?: { url: string }) => void) |

网页开始加载时触发该回调,且只在主frame触发,iframe或者frameset的内容加载时不会触发此回调。
url:页面的URL地址。

| +| onPageEnd(callback: (event?: { url: string }) => void) |

网页加载完成时触发该回调,且只在主frame触发。
url:页面的URL地址。

| +| onProgressChange(callback: (event?: { newProgress: number }) => void) |

网页加载进度变化时触发该回调。
newProgress:新的加载进度,取值范围为0到100的整数。

| +| onTitleReceive(callback: (event?: { title: string }) => void) |

网页document标题更改时触发该回调。
title:document标题内容。

| ### ConsoleMessage对象说明 - 接口 - | 接口名称 | 功能描述 | - | ------------------------------- | ---------------------- | - | getLineNumber(): number | 获取ConsoleMessage的行数。 | + | 接口名称 | 功能描述 | + | ------------------------------- | ------------------------------ | + | getLineNumber(): number | 获取ConsoleMessage的行数。 | | getMessage(): string | 获取ConsoleMessage的日志信息。 | | getMessageLevel(): MessageLevel | 获取ConsoleMessage的信息级别。 | - | getSourceId(): string | 获取ConsoleMessage的源的Id。 | + | getSourceId(): string | 获取网页源文件路径和名字。 | - MessageLevel枚举说明 @@ -95,16 +89,16 @@ ohos.permission.READ_USER_STORAGE | Log | 日志级别。 | | Warn | 警告级别。 | -### JsResult 对象说明 +### JsResult对象说明 Web组件返回的弹窗确认或弹窗取消功能对象。 - 接口 - | 接口名称 | 功能描述 | - | --------------------- | ------------ | - | handleCancel(): void |

取消弹窗。

| - | handleConfirm(): void |

确认弹窗。

| + | 接口名称 | 功能描述 | + | --------------------- | ------------------------------------ | + | handleCancel(): void |

通知web组件用户取消弹窗操作。

| + | handleConfirm(): void |

通知web组件用户确认弹窗操作。

| ### WebResourceError对象说明 @@ -119,30 +113,42 @@ Web组件返回的弹窗确认或弹窗取消功能对象。 - 接口 - | 接口名称 | 功能描述 | - | ----------------------------------- | ------------------ | - | getRequestHeader(): Array\ | 获取请求头信息。 | - | getRequestUrl(): string | 获取请求的url信息。 | - | isMainFrame(): boolean | 获取请求是否时为了获取主窗口的信息。 | - | isRedirect(): boolean | 获取请求是否重定向。 | - | isRequestGesture(): boolean | 获取请求是否与手势关联。 | + | 接口名称 | 功能描述 | + | ------------------------------------------------------ | ---------------------------------------- | + | getRequestHeader(): Array\<[Header](#Header对象说明)\> | 获取资源请求头信息。 | + | getRequestUrl(): string | 获取资源请求的URL信息。 | + | isMainFrame(): boolean | 判断资源请求是否为主frame。 | + | isRedirect(): boolean | 判断资源请求是否被服务端重定向。 | + | isRequestGesture(): boolean | 获取资源请求是否与手势(如点击)相关联。 | + +### Header对象说明 + +Web组件返回的请求/响应头对象。 + +- 参数 + + | 参数名称 | 参数描述 | + | ----------- | ---------------------- | + | headerKey: string |

请求/响应头的key。

| + | headerValue: string |

请求/响应头的value。

| + ### WebResourceResponse对象说明 - 接口 - | 接口名称 | 功能描述 | - | ------------------------------------ | ----------- | - | getReasonMessage(): string | 获取响应的状态码描述。 | - | getResponseCode(): number | 获取响应的状态码。 | - | getResponseData(): string | 获取响应数据。 | - | getResponseEncoding(): string | 获取响应的编码。 | - | getResponseHeader(): Array\ | 获取响应头信息。 | - | getResponseMimeType(): string | 获取响应的媒体类型。 | + | 接口名称 | 功能描述 | + | ------------------------------------ | -------------------------------- | + | getReasonMessage(): string | 获取资源响应的状态码描述。 | + | getResponseCode(): number | 获取资源响应的状态码。 | + | getResponseData(): string | 获取资源响应数据。 | + | getResponseEncoding(): string | 获取资源响应的编码。 | + | getResponseHeader(): Array\<[Header](#Header对象说明)\> | 获取资源响应头。 | + | getResponseMimeType(): string | 获取资源响应的媒体(MIME)类型。 | ## WebController -Web 组件的控制器。 +通过webController可以控制web组件各种行为,或获取web组件的配置信息。 ### 创建对象 @@ -154,19 +160,19 @@ webController: WebController = new WebController() accessBackward(): boolean -当前页面是否可后退。 +当前页面是否可后退,即当前页面是否有返回历史记录。 ### accessForward accessForward(): boolean -当前页面是否可前进。 +当前页面是否可前进,即当前页面是否有前进历史记录。 ### accessStep accessStep(step: number): boolean -当前页面是否可前进或者后退step步。 +当前页面是否可前进或者后退给定的step步。 - 参数 @@ -178,124 +184,126 @@ accessStep(step: number): boolean backward(): void -页面后退。 +按照历史栈,后退一个页面。一般结合accessBackward一起使用。 ### deleteJavaScriptRegister deleteJavaScriptRegister(name: string): void -清空指定对象已注册的JavaScript方法。 +删除通过registerJavaScriptProxy注册到window上的指定name的应用侧JavaScript对象。 - 参数 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | ---- | ------ | ---- | ---- | ----------------------- | - | name | string | 是 | - | 注册对象的名称,与HTML中调用的对象名一致。 | + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | + | ------ | -------- | ---- | ------ | ------------------------------------------------------------ | + | name | string | 是 | - | 注册对象的名称,可在网页侧JavaScript中通过此名称调用应用侧JavaScript对象。 | ### forward forward(): void -页面前进。 +按照历史栈,前进一个页面。一般结合accessForward一起使用。 ### getHitTest getHitTest(): HitTestType -获取当前已点击的对象类型。 +获取当前被点击区域的元素类型。 - HitTestType枚举说明 - | 名称 | 描述 | - | ------- | -------------------------------- | - | Edit | 可编辑的区域。 | - | Email | 邮件地址。 | - | Http | HTTP网址的HTML \标签。 | - | HttpImg | HTTP网址与\标签组成的HTML \标签。 | - | Img | HTML \标签。 | - | Map | 地图地址。 | - | Phone | 电话号码。 | - | Unknown | 未知内容。 | + | 名称 | 描述 | + | ------------- | ----------------------------------------- | + | EditText | 可编辑的区域。 | + | Email | 电子邮件地址。 | + | HttpAnchor | 超链接。其src为http。 | + | HttpAnchorImg | 带有超链接的图片,其中超链接的src为http。 | + | Img | HTML::img标签。 | + | Map | 地理地址。 | + | Phone | 电话号码。 | + | Unknown | 未知内容。 | ### loadData loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }): void -加载数据。 +baseUrl为空时,通过”data“协议加载指定的一段字符串。 + +当baseUrl为”data“协议时,编码后的data字符串将被web组件作为”data"协议加载。 + +当baseUrl为“http/https"协议时,编码后的data字符串将被web组件以类似loadUrl的方式以非编码字符串处理。 - options参数说明 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | ---------- | ------ | ---- | ---- | -------- | - | data | string | 是 | - | 需要加载的数据。 | - | mimeType | string | 是 | - | 媒体类型。 | - | encoding | string | 是 | - | 编码类型。 | - | baseUrl | string | 否 | - | 基础URL。 | - | historyUrl | string | 否 | - | 历史URL。 | + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | + | ---------- | -------- | ---- | ------ | ------------------------------------------------------------ | + | data | string | 是 | - | 按照”Base64“或者”URL"编码后的一段字符串。 | + | mimeType | string | 是 | - | 媒体类型(MIME)。 | + | encoding | string | 是 | - | 编码类型,具体为“Base64"或者”URL编码。 | + | baseUrl | string | 否 | - | 指定的一个URL路径(“http”/“https”/"data"协议),并由web组件赋值给window.origin。 | + | historyUrl | string | 否 | - | 历史记录URL。非空时,可被历史记录管理,实现前后后退功能。当baseUrl为空时,此属性无效。 | ### loadUrl -loadUrl(options:{ url: string, headers?: Array<{ key: string, value: string }> }): void +loadUrl(options:{ url: string, headers?: Array\ }): void + +使用指定的http头加载指定的URL。 -加载URL。 +通过loadUrl注入的对象只在当前document有效,即通过loadUrl导航到新的页面会无效。 + +而通过registerJavaScriptProxy注入的对象,在loadUrl导航到新的页面也会有效。 - options参数说明 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | ------- | ------------------------------------- | ---- | ---- | ---------- | - | url | string | 是 | - | 需要加载的 URL。 | - | headers | Array<{ key: string, value: string }> | 否 | [] | HTTP附加信息。 | + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | + | ------- | ------------------------------------- | ---- | ------ | --------------------- | + | url | string | 是 | - | 需要加载的 URL。 | + | headers | Array\<[Header](#Header对象说明)\> | 否 | [] | URL的附加HTTP请求头。 | ### onActive onActive(): void -页面重新激活。当Web被重新激活为活跃状态时,执行此方法。 +调用此接口通知web组件进入前台激活状态。 ### onInactive onInactive(): void -页面暂停渲染。当Web被切换到后台不可见状态时,执行此方法。 +调用此接口通知web组件进入未激活状态。 ### refresh refresh(): void -刷新页面。 +调用此接口通知web组件刷新网页。 ### registerJavaScriptProxy -registerJavaScriptProxy(options: { obj: object, name: string, methodList: Array\ }): void +registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\ }): void -将JavaScript对象与方法注册到Web内核,可被已加载的HTML直接调用。注册后,须调用refresh接口生效。 +注入JavaScript对象到window对象中,并在window对象中调用该对象的方法。注册后,须调用refresh接口生效。 - options 参数说明 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | ---------- | --------------- | ---- | ---- | ----------------------- | - | obj | object | 是 | - | 参与注册的对象。 | - | name | string | 是 | - | 注册对象的名称,与HTML中调用的对象名一致。 | - | methodList | Array\ | 是 | - | 参与注册的方法。 | + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | + | ---------- | --------------- | ---- | ------ | ------------------------------------------------------------ | + | object | object | 是 | - | 参与注册的应用侧JavaScript对象。只能声明方法,不能声明属性 。其中方法的参数和返回类型只能为string,number,boolean | + | name | string | 是 | - | 注册对象的名称,与window中调用的对象名一致。注册后window对象可以通过此名字访问应用侧JavaScript对象。 | + | methodList | Array\ | 是 | - | 参与注册的应用侧JavaScript对象的方法。 | ### runJavaScript runJavaScript(options: { script: string, callback?: (result: string) => void }): void -执行JavaScript脚本。 +异步执行JavaScript脚本,并通过回调方式返回脚本执行的结果。runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 - options参数说明 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | -------- | ------------------------ | ---- | ---- | ------------------------------------ | - | script | string | 是 | - | JavaScript脚本。 | - | callback | (result: string) => void | 否 | - | 回调执行JavaScript脚本结果,默认result为null字符串。 | - -### requestFocus - -requestFocus(): void - -Web组件获焦。 + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | + | -------- | ------------------------ | ---- | ------ | ------------------------------------------------------------ | + | script | string | 是 | - | JavaScript脚本。 | + | callback | (result: string) => void | 否 | - | 回调执行JavaScript脚本结果。JavaScript脚本若执行失败或无返回值时,返回null。 | ### stop diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components.md index 5e19ebf33efffbcac9e972e65124ff8052cdbb04..0d0457df9a07e9e7253875cc5aefbad4d7fed2dc 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components.md @@ -1,42 +1,32 @@ # 基础组件 -- **[Blank](ts-basic-components-blank.md)** - -- **[Button](ts-basic-components-button.md)** - -- **[DataPanel](ts-basic-components-datapanel.md)** - -- **[DatePicker](ts-basic-components-datepicker.md)** - -- **[Divider](ts-basic-components-divider.md)** - -- **[Image](ts-basic-components-image.md)** - -- **[ImageAnimator](ts-basic-components-imageanimator.md)** - -- **[Progress](ts-basic-components-progress.md)** - -- **[QRCode](ts-basic-components-qrcode.md)** - -- **[Rating](ts-basic-components-rating.md)** - -- **[Span](ts-basic-components-span.md)** - -- **[Slider](ts-basic-components-slider.md)** - -- **[Text](ts-basic-components-text.md)** - -- **[TextArea](ts-basic-components-textarea.md)** - -- **[TextInput](ts-basic-components-textinput.md)** - -- **[TextPicker](ts-basic-components-textpicker.md)** - -- **[TextTimer](ts-basic-components-texttimer.md)** - -- **[Toggle](ts-basic-components-toggle.md)** - -- **[Select](ts-basic-components-select.md)** -- **[TextClock](ts-basic-components-textClock.md)** - -- **[Xcomponent](ts-basic-components-xcomponent.md)** \ No newline at end of file +- [Blank](ts-basic-components-blank.md) +- [Button](ts-basic-components-button.md) +- [Checkbox](ts-basic-components-checkbox.md) +- [CheckboxGroup](ts-basic-components-checkboxgroup.md) +- [DataPanel](ts-basic-components-datapanel.md) +- [DatePicker](ts-basic-components-datepicker.md) +- [Divider](ts-basic-components-divider.md) +- [Gauge](ts-basic-components-gauge.md) +- [Image](ts-basic-components-image.md) +- [ImageAnimator](ts-basic-components-imageanimator.md) +- [Marquee](ts-basic-components-marquee.md) +- [LoadingProgress](ts-basic-components-loadingprogress.md) +- [Progress](ts-basic-components-progress.md) +- [QRCode](ts-basic-components-qrcode.md) +- [Radio](ts-basic-components-radio.md) +- [Rating](ts-basic-components-rating.md) +- [Select](ts-basic-components-select.md) +- [Slider](ts-basic-components-slider.md) +- [Span](ts-basic-components-span.md) +- [Text](ts-basic-components-text.md) +- [TextArea](ts-basic-components-textarea.md) +- [TextInput](ts-basic-components-textinput.md) +- [TextPicker](ts-basic-components-textpicker.md) +- [TextTimer](ts-basic-components-texttimer.md) +- [TimePicker](ts-basic-components-timepicker.md) +- [Toggle](ts-basic-components-toggle.md) +- [TextClock](ts-basic-components-textclock.md) +- [Web](ts-basic-components-web.md) +- [Xcomponent](ts-basic-components-xcomponent.md) +- [PluginComponent](ts-basic-components-plugincomponent.md) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-container.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-container.md index 5593bd74eb70c53c8d11d0a87d587ad42b4ec5fd..434e86ae5b7633e4f45625dfc6c0b77e2bbdb407 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-container.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-container.md @@ -1,45 +1,28 @@ # 容器组件 -- **[AlphabetIndexer](ts-container-alphabet-indexer.md)** - -- **[Badge](ts-container-badge.md)** - -- **[Column](ts-container-column.md)** - -- **[ColumnSplit](ts-container-columnsplit.md)** - -- **[Counter](ts-container-counter.md)** - -- **[Flex](ts-container-flex.md)** - -- **[GridContainer](ts-container-gridcontainer.md)** - -- **[Grid](ts-container-grid.md)** - -- **[GridItem](ts-container-griditem.md)** - -- **[List](ts-container-list.md)** - -- **[ListItem](ts-container-listitem.md)** - -- **[Navigator](ts-container-navigator.md)** - -- **[Navigation](ts-basic-components-navigation.md)** - -- **[Panel](ts-container-panel.md)** - -- **[Row](ts-container-row.md)** - -- **[RowSplit](ts-container-rowsplit.md)** - -- **[Scroll](ts-container-scroll.md)** - -- **[ScrollBar](ts-basic-components-scrollbar.md)** - -- **[Stack](ts-container-stack.md)** - -- **[Swiper](ts-container-swiper.md)** - -- **[Tabs](ts-container-tabs.md)** - -- **[TabContent](ts-container-tabcontent.md)** \ No newline at end of file +- [AlphabetIndexer](ts-container-alphabet-indexer.md) +- [Badge](ts-container-badge.md) +- [Column](ts-container-column.md) +- [ColumnSplit](ts-container-columnsplit.md) +- [Counter](ts-container-counter.md) +- [Flex](ts-container-flex.md) +- [GridContainer](ts-container-gridcontainer.md) +- [Grid](ts-container-grid.md) +- [GridItem](ts-container-griditem.md) +- [List](ts-container-list.md) +- [ListItem](ts-container-listitem.md) +- [Navigator](ts-container-navigator.md) +- [Navigation](ts-basic-components-navigation.md) +- [Panel](ts-container-panel.md) +- [Row](ts-container-row.md) +- [RowSplit](ts-container-rowsplit.md) +- [Scroll](ts-container-scroll.md) +- [ScrollBar](ts-basic-components-scrollbar.md) +- [SideBarContainer](ts-container-sidebarcontainer.md) +- [Stack](ts-container-stack.md) +- [Swiper](ts-container-swiper.md) +- [Tabs](ts-container-tabs.md) +- [TabContent](ts-container-tabcontent.md) +- [Refresh](ts-container-refresh.md) +- [Stepper](ts-basic-components-stepper.md) +- [StepperItem](ts-basic-components-stepperitem.md) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components.md b/zh-cn/application-dev/reference/arkui-ts/ts-components.md index 87d8ac0b7bf2cd82e0e3970515a961485953fcce..5864284d1386a0c6fc84bcc46ca523d23305d891 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components.md @@ -1,11 +1,12 @@ # 组件 -- **[通用](ts-universal-components.md)** +- [通用](ts-universal-components.md) -- **[基础组件](ts-basic-components.md)** +- [基础组件](ts-basic-components.md) -- **[容器组件](ts-components-container.md)** +- [容器组件](ts-components-container.md) -- **[绘制组件](ts-drawing-components.md)** +- [绘制组件](ts-drawing-components.md) +- [媒体组件](ts-media-components.md) -- **[画布组件](ts-components-canvas.md)** \ No newline at end of file +- [画布组件](ts-components-canvas.md) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-global-ui-methods.md b/zh-cn/application-dev/reference/arkui-ts/ts-global-ui-methods.md index 9cbebba1b2482ea3f97dba93eaffe11cf7b74ca2..56df0dede9b4377728968ca02fab680d1ab99716 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-global-ui-methods.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-global-ui-methods.md @@ -1,7 +1,10 @@ # 全局UI方法 - -- **[图片缓存](ts-methods-image-cache.md)** - -- **[媒体查询](ts-methods-media-query.md)** - -- **[弹窗](ts-methods-popup-window.md)** \ No newline at end of file +- [图片缓存](ts-methods-image-cache.md) +- 弹窗 + - [警告弹窗](ts-methods-alert-dialog-box.md) + - [列表选择弹窗](ts-methods-action-sheet.md) + - [自定义弹窗](ts-methods-custom-dialog-box.md) + - [日期选择弹窗](ts-methods-datepicker-dialog.md) + - [时间选择弹窗](ts-methods-timepicker-dialog.md) + - [文本选择弹窗](ts-methods-textpicker-dialog.md) +- [菜单](ts-methods-menu.md) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-media-components.md b/zh-cn/application-dev/reference/arkui-ts/ts-media-components.md index cc86617a935fd1c5c43fbc159052d6b8f86c2ff9..483d45881aa5674684da59c5b7f727912239c847 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-media-components.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-media-components.md @@ -1,5 +1,3 @@ # 媒体组件 -- **[Video](ts-media-components-video.md)** - -- **[Web](ts-media-components-web.md)** \ No newline at end of file +- **[Video](ts-media-components-video.md)** \ No newline at end of file diff --git a/zh-cn/application-dev/ui/Readme-CN.md b/zh-cn/application-dev/ui/Readme-CN.md index 1dea595ff58ca02b730ca0664e1edb8eda7a4a15..7b70cf8f8248b4ef6ae19cb09d11c4c3e569869a 100755 --- a/zh-cn/application-dev/ui/Readme-CN.md +++ b/zh-cn/application-dev/ui/Readme-CN.md @@ -56,6 +56,8 @@ - [应用代码文件访问规则](ts-framework-file-access-rules.md) - [js标签配置](ts-framework-js-tag.md) - 资源访问 + - [访问应用资源](ts-application-resource-access.md) + - [访问系统资源](ts-system-resource-access.md) - [媒体资源类型说明](ts-media-resource-type.md) - [像素单位](ts-pixel-units.md) - [类型定义](ts-types.md) diff --git a/zh-cn/device-dev/driver/driver-peripherals-sensor-des.md b/zh-cn/device-dev/driver/driver-peripherals-sensor-des.md index 65c872e14154ba5cee8c47aa9a47f8d00cc75bff..79c28c5e9cb812c1630b0f83f9f7b6372e5af61c 100755 --- a/zh-cn/device-dev/driver/driver-peripherals-sensor-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-sensor-des.md @@ -70,207 +70,56 @@ Sensor驱动模型对外开放的API接口能力如下: - 提供同一类型Sensor器件驱动归一接口, 寄存器配置解析操作接口,总线访问抽象接口,平台抽象接口。 - 提供开发者实现的能力接口:依赖HDF驱动框架的HCS(HDF Configuration Source)配置管理,根据同类型Sensor差异化配置,实现Sensor器件参数序列化配置和器件部分操作接口,简化Sensor器件驱动开发。 -Sensor驱动模型对外开放的API接口能力的具体实现参考[表1](#table203963834718): - -**表 1** Sensor驱动模型对外API接口功能介绍 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

功能分类

-

接口名

-

功能描述

-

查询操作

-

int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count)

-

获取系统中注册的所有传感器信息,一组完整传感器信息包括传感器名字、设备厂商、固件版本号、硬件版本号、传感器类型编号、传感器标识、最大量程、精度、功耗。

-

配置操作

-

int32_t Enable(int32_t sensorId)

-

使能指定传感器设备,只有数据订阅者使能传感器后,才能获取订阅的传感器数据。

-

int32_t Disable(int32_t sensorId)

-

去使能指定传感器设备。

-

int32_t SetBatch(iint32_t sensorId, int64_t samplingInterval, int64_t reportInterval)

-

设置指定传感器的数据采样间隔和数据上报间隔。

-

int32_t SetMode(int32_t sensorId, int32_t mode)

-

设置指定传感器的工作模式,不同的工作模式,上报数据方式不同。

-

int32_t SetOption(int32_t sensorId, uint32_t option)

-

设置指定传感器量程,精度等可选配置。

-

数据订阅操作

-

int32_t Register(int32_t groupId, RecordDataCallback cb);

-

订阅者根据不同groupId注册传感器数据回调函数,系统会将获取到的传感器数据上报给订阅者。

-

int32_t Unregister(int32_t groupId, RecordDataCallback cb)

-

订阅者根据groupId和回调函数注销对应订阅者的传感器数据回调函数。

-
- - -Sensor驱动模型对驱动开发者开放的功能接口,驱动开发者无需实现,直接使用,参考[表2](#table1156812588320): +Sensor驱动模型对外开放的API接口能力的具体实现参考[表1](#PinCntlrMethod成员的回调函数功能说明): + +**表 1** PinCntlrMethod成员的回调函数功能说明 + +| 接口名 | 功能描述 | +| ----- | -------- | +| int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count) | 获取系统中注册的所有传感器信息,一组完整传感器信息包括传感器名字、设备厂商、固件版本号、硬件版本号、传感器类型编号、传感器标识、最大量程、精度、功耗。 | +| int32_t Enable(int32_t sensorId) | 使能指定传感器设备,只有数据订阅者使能传感器后,才能获取订阅的传感器数据。 | +| int32_t Disable(int32_t sensorId) | 去使能指定传感器设备。 | +| int32_t SetBatch(iint32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | 设置指定传感器的数据采样间隔和数据上报间隔。 | +| int32_t SetMode(int32_t sensorId, int32_t mode) | 设置指定传感器的工作模式,不同的工作模式,上报数据方式不同。 | +| int32_t SetOption(int32_t sensorId, uint32_t option) | 设置指定传感器量程,精度等可选配置。 | +| int32_t Register(int32_t groupId, RecordDataCallback cb) | 订阅者根据不同groupId注册传感器数据回调函数,系统会将获取到的传感器数据上报给订阅者。 | +| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | 订阅者根据groupId和回调函数注销对应订阅者的传感器数据回调函数。 | + + + +Sensor驱动模型对驱动开发者开放的功能接口,驱动开发者无需实现,直接使用,参考[表2](#Sensor驱动模型对驱动开发者开放的功能接口列表): **表2** Sensor驱动模型对驱动开发者开放的功能接口列表 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

功能分类

-

接口名

-

功能描述

-

设备管理操作接口

-

int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo)

-

添加当前类型的传感器设备到传感器设备管理。

-

int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo)

-

删除传感器设备管理里指定的传感器设备。

-

int32_t ReportSensorEvent(const struct SensorReportEvent *events)

-

上报指定类型传感器的数据到用户侧。

-

Sensor抽象总线

-

int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, uint16_t dataLen)

-

按照配置的总线方式,读取传感器寄存器配置数据。

-

int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t len)

-

按照配置的总线方式,将传感器配置数据写入寄存器。

-

通用配置操作接口

-

int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group);

-

根据传感器总线类型信息,下发寄存器分组配置。

-

配置解析操作接口

-

-

int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config)

-

根据传感器设备HCS资源配置,获取传感器信息,总线配置信息,属性配置等基本配置信息,并初始化对应的基本配置数据结构体。

-

int32_t ParseSensorRegConfig(struct SensorCfgData *config)

-

根据传感器设备HCS资源配置,解析寄存器分组信息,并初始化配置数据结构体。

-

void ReleaseSensorAllRegConfig(struct SensorCfgData *config)

-

释放传感器配置数据结构体里分配的资源。

-

int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg)

-

获取传感器总线句柄信息。

-

int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg)

-

释放传感器句柄信息。

-
- - - -Sensor驱动模型要求驱动开发者实现的接口功能,参考[表3](#table1083014911336): +| 接口名 | 功能描述 | +| ----- | -------- | +| int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | 添加当前类型的传感器设备到传感器设备管理。 | +| int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | 删除传感器设备管理里指定的传感器设备。 | +| int32_t ReportSensorEvent(const struct SensorReportEvent *events) | 上报指定类型传感器的数据到用户侧。 | +| int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, uint16_t dataLen) | 按照配置的总线方式,读取传感器寄存器配置数据。 | +| int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t len) | 按照配置的总线方式,将传感器配置数据写入寄存器。 | +| int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group); | 根据传感器总线类型信息,下发寄存器分组配置。 | +| int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config) | 根据传感器设备HCS资源配置,获取传感器信息,总线配置信息,属性配置等基本配置信息,并初始化对应的基本配置数据结构体。 | +| int32_t ParseSensorRegConfig(struct SensorCfgData *config) | 根据传感器设备HCS资源配置,解析寄存器分组信息,并初始化配置数据结构体。 | +| void ReleaseSensorAllRegConfig(struct SensorCfgData *config) | 释放传感器配置数据结构体里分配的资源。 | +| int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg) | 获取传感器总线句柄信息。 | +| int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg) | 释放传感器句柄信息。 | + -**表 3** Sensor驱动模型要求驱动开发者实现的接口列表 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

功能分类

-

接口名

-

功能描述

-

基本功能操作

-

int32_t init(void)

-

传感器设备探测成功后,需要对传感器设备初始化配置。

-

int32_t Enable(void)

-

根据当前传感器设备的HCS配置,下发传感器设备使能操作组的寄存器配置。

-

int32_t Disable(void)

-

根据当前传感器设备的HCS配置,下发传感器设备去使能操作组的寄存器配置。

-

int32_t SetBatch(int64_t samplingInterval, int64_t reportInterval)

-

根据数据采样率和数据上报间隔,配置当前传感器设备的数据上报线程处理时间。

-

int32_t SetMode(int32_t mode)

-

配置当前传感器设备数据上报方式。

-

int32_t SetOption(uint32_t option)

-

根据可选配置、下发量程和精度等寄存器配置。

-

void ReadSensorData(void)

-

实现传感器的数据读取函数。

-
+Sensor驱动模型要求驱动开发者实现的接口功能,参考[表3](#Sensor驱动模型要求驱动开发者实现的接口列表): + +**表 3** Sensor驱动模型要求驱动开发者实现的接口列表 +| 接口名 | 功能描述 | +| ----- | -------- | +| int32_t init(void) | 传感器设备探测成功后,需要对传感器设备初始化配置。 | +| int32_t Enable(void) | 根据当前传感器设备的HCS配置,下发传感器设备使能操作组的寄存器配置。 | +| int32_t Disable(void) | 根据当前传感器设备的HCS配置,下发传感器设备去使能操作组的寄存器配置。 | +| int32_t SetBatch(int64_t samplingInterval, int64_t reportInterval) | 根据数据采样率和数据上报间隔,配置当前传感器设备的数据上报线程处理时间。 | +| int32_t SetMode(int32_t mode) | 配置当前传感器设备数据上报方式。 | +| int32_t SetOption(uint32_t option) | 根据可选配置、下发量程和精度等寄存器配置。 | +| void ReadSensorData(void) | 实现传感器的数据读取函数。 | 接口实现参考[开发步骤](#section7893102915819)章节。 diff --git "a/zh-cn/readme/\347\252\227\345\217\243\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\347\252\227\345\217\243\345\255\220\347\263\273\347\273\237.md" index d86418ff9e9c03149ebbb0a0bea1f81326a4acd2..a7afe7ce45d37507fa779b7f0dd7117fccb87f09 100644 --- "a/zh-cn/readme/\347\252\227\345\217\243\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\347\252\227\345\217\243\345\255\220\347\263\273\347\273\237.md" @@ -3,6 +3,7 @@ ## 简介 **窗口子系统** 提供窗口管理和Display管理的基础能力,是系统图形界面显示所需的基础子系统。其主要的结构如图1所示。 + **图 1** 窗口子系统架构图 ![窗口子系统架构图](./figures/WindowManager.png) @@ -24,7 +25,8 @@ Display管理服务,提供Display信息、屏幕截图、屏幕亮灭和亮度处理控制,并处理Display与Screen映射关系。 ## 目录 -``` + +```text foundation/windowmanager/ ├── dm # Display Manager Client实现代码 ├── dmserver # Display Manager Server实现代码 @@ -40,8 +42,9 @@ foundation/windowmanager/ ``` ## 约束 + - 语言版本 - - C++11或以上 + - C++11或以上 ## 接口说明 @@ -49,7 +52,8 @@ foundation/windowmanager/ - [Display](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-display.md) ## 相关仓 + - graphic_standard - ace_ace_engine - aafwk_standard -- multimodalinput_input \ No newline at end of file +- multimodalinput_input diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md new file mode 100644 index 0000000000000000000000000000000000000000..935207b37dc9be7fd1db88d848000dfbbc300464 --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md @@ -0,0 +1,126 @@ +# OpenHarmony 3.0.2 LTS + + +## 版本概述 + +此版本为OpenHarmony-3.0-LTS分支上的维护版本,基于OpenHarmony-v3.0.1-LTS版本修复一些缺陷及安全问题,通过集成验证后发布最新且稳定的标签版本。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.0.2 LTS | NA | +| SDK | 3.0.0.0(API Version 7 release) | NA | +| HUAWEI DevEco Studio(可选) | 3.0 Beta1 | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 2.2 Beta2 | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 通过repo获取 + +**方式一(推荐)**:通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.2-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**方式二**:通过repo + https 下载。 + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.2-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + + **表2** 获取源码路径 + +| **LTS版本源码** | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.0.2 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.0.2/code-v3.0.2-LTS.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.0.2/code-v3.0.2-LTS.tar.gz.sha256) | +| 标准系统解决方案(二进制) | 3.0.2 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.0.2/standard.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.0.2/standard.tar.gz.sha256) | +| 轻量系统Hi3861解决方案(二进制) | 3.0.2 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.0.2/hispark_pegasus.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.0.2/hispark_pegasus.tar.gz.sha256) | +| 小型系统Hi3516解决方案-LiteOS(二进制) | 3.0.2 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.0.2/hispark_taurus.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.0.2/hispark_taurus.tar.gz.sha256) | +| 小型系统Hi3516解决方案-Linux(二进制) | 3.0.2 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.0.2/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.0.2/hispark_taurus_linux.tar.gz.sha256) | + + +## 更新说明 + +本版本在OpenHarmony v3.0.1 LTS的基础上有如下变更。 + + +### 特性变更 + +当前维护版本不涉及新需求及新特性的接纳与变更。 + + +### API变更 + +此版本不涉及API变更。 + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +## 修复缺陷列表 + + **表3** 轻量和小型系统解决的缺陷ISSUE列表 + +| ISSUE单号 | 问题描述 | +| -------- | -------- | +| [I4UZ7U](https://gitee.com/openharmony/xts_acts/issues/I4UZ7U?from=project-issue) | 小型系统执行XTS测试时概率有35条失败项 | +| [I4V2DN](https://gitee.com/openharmony/xts_acts/issues/I4V2DN?from=project-issue) | ActsLwipTest模块测试中存在两条用例执行超时的失败 | +| [I4V3KC](https://gitee.com/openharmony/xts_acts/issues/I4V3KC?from=project-issue) | 分布式调度子系统testPublish0010测试用例执行失败 | +| [I4URGA](https://gitee.com/openharmony/applications_sample_camera/issues/I4URGA?from=project-issue) | 设置界面搜WLAN信号时概率出现蓝屏 | +| [I4SDCK](https://gitee.com/openharmony/aafwk_aafwk_lite/issues/I4SDCK?from=project-issue) | 小型系统HI 3516 GetSrcPath /GetDataPath 获取路径为空或者乱码 | +| [I4T6KZ](https://gitee.com/openharmony/communication_dsoftbus/issues/I4T6KZ) | 测试传输相关用例时在 SendMessage SendData4Data处失败 | +| I4UOUS | Hi3516小型系统 串口界面的回显日志打印了明文密码 | +| [I4OWZO](https://gitee.com/openharmony/third_party_toybox/issues/I4OWZO) | toybox mv命令移动nfs路径下的文件出现异常提示 | +| [I4NCSF](https://gitee.com/openharmony/graphic_ui/issues/I4NCSF) | 图形子系统UI模块,直线型指针无法实时刷新 | +| [I4NU92](https://gitee.com/openharmony/communication_wifi/issues/I4NU92) | Hi3516 Linux ActsLwipTest.bin测试套测试存在一条失败项 | +| [I4NVCK](https://gitee.com/openharmony/applications_sample_camera/issues/I4NVCK) | audio capture无法正常运行 | +| [I4NESQ](https://gitee.com/openharmony/kernel_liteos_a/issues/I4NESQ) | los_disk_cache_clear有条件编译错误 | +| [I4O67U](https://gitee.com/openharmony/kernel_liteos_a/issues/I4O67U) | 修复Ctrl+C会终止所有进程的问题 | +| [I4R4D3](https://gitee.com/openharmony/kernel_liteos_m/issues/I4R4D3) | pthread_create创建的线程未设置detach属性,主动退出后,OsGetAllTskInfo调用后,相关的任务名为乱码 | +| [I4R4A5](https://gitee.com/openharmony/kernel_liteos_m/issues/I4R4A5) | pthread_cond_timedwait接口实现存在计算溢出的问题 | +| [I4QJT4](https://gitee.com/openharmony/drivers_adapter_khdf_linux/issues/I4QJT4) | 修复UartRead test case 失败问题 | +| [I4U1DM](https://gitee.com/openharmony/distributedschedule_samgr_lite/issues/I4U1DM) | samgr 的 QUEUE_Pop 函数在调用 LFQUE_Pop 函数时未加锁,存在潜在的数据竞争 | + + **表4** 标准系统解决的缺陷ISSUE列表 + +| ISSUE单号 | 问题描述 | +| -------- | -------- | +| [I4UJNU](https://gitee.com/openharmony/applications_settings/issues/I4UJNU) | 通过设置连接WLAN时,WLAN密码在hilog日志中明文打印 | +| [I4MSWM](https://gitee.com/openharmony/xts_acts/issues/I4MSWM?from=project-issue) | XT测试执行测试ActsFaultLoggerTest模块faultloggertest用例时有1条失败项 | +| [I4MSVV](https://gitee.com/openharmony/xts_acts/issues/I4MSVV?from=project-issue) | XTS测试执行测试ActsHiCollieCppTest模块HiCollieCppTest用例时有3条失败项 | +| [I4PPXV](https://gitee.com/openharmony/appexecfwk_standard/issues/I4PPXV?from=project-issue) | 打开应用后再退出到桌面,桌面应用图标丢失 | +| [I4OF9A](https://gitee.com/openharmony/distributeddatamgr_file/issues/I4OF9A?from=project-issue) | file.readText接口读取的text值不稳定 | +| [I4OWWM](https://gitee.com/openharmony/xts_acts/issues/I4OWWM) | WeekPluralNumbertest模块对应json文件配置问题,执行用例时报"required device does not exist"导致此测试套无法执行 | +| [I4OUVQ](https://gitee.com/openharmony/xts_tools/issues/I4OUVQ?from=project-issue) | XTS JS用例反复压力测试过程中系统卡死,无法进行测试 | +| [I4NMXQ](https://gitee.com/openharmony/xts_acts/issues/I4NMXQ?from=project-issue) | XTS执行storagefileioperformancejstest和storagefilestabilityjstest测试套无法执行起来 | +| [I4NTKG](https://gitee.com/openharmony/xts_acts/issues/I4NTKG) | 执行xts测试套WeekPluralNumberTest出现两条失败项 | +| [I4NPHG](https://gitee.com/openharmony/xts_acts/issues/I4NPHG?from=project-issue) | timer定时器测试套TimerJSApiTest.hap未随版本编译出来 | + + + **表5** 安全漏洞合入列表 + +| ISSUE单号 | 问题描述 | +| -------- | -------- | +| I4QT0K | 修复third_party_mbedtls组件CVE-2021-44732和CVE-2021-45450安全漏洞 | +| I4NZ16 | 更新third_party_sqlite组件到3.36.0版本,同时修复CVE-2021-36690安全漏洞 | +| I4NW0B | 修复third_party_gstreamer组件CVE-2021-3522安全漏洞 | +| I4SR8C | 修复third_party_openssl组件 CVE-2021-4160修复 | +| I4U4B0 | 更新third_party_expat组件到2.4.1版本,修复CVE-2022-25313/25314/25315/25235/252256/23990/23852/22827/46143/45960等安全漏洞 | diff --git a/zh-cn/release-notes/Readme.md b/zh-cn/release-notes/Readme.md index b4f5de9c3a291d9a08d943cff32e30969e5d8343..d40a73d8785ef056c10a13926d70dc64689aae07 100644 --- a/zh-cn/release-notes/Readme.md +++ b/zh-cn/release-notes/Readme.md @@ -1,6 +1,7 @@ # OpenHarmony Release Notes ## OpenHarmony 3.x Releases - [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) +- [OpenHarmony v3.0.2 LTS (2022-03-18)](OpenHarmony-v3.0.2-LTS.md) - [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md) - [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md)