diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 53e3ca5aeaa25ecea55f3e27272043e6b533e594..df633d8449281b12557bb3d39f333f97148af1a4 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -7,7 +7,7 @@ A relational database (RDB) store allows you to operate local data with or witho ## Available APIs -Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For details about the APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). +Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). ### Creating or Deleting an RDB Store @@ -17,8 +17,8 @@ The following table describes the APIs for creating and deleting an RDB store. | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> | Obtains an **RdbStoreV9** instance. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: version of the RDB store. Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported.| -| deleteRdbStoreV9(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: context of the application or function.
- **name**: name of the RDB store to delete.| +| getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | Obtains an **RdbStore** object. This API uses a promise to return the result. You can set parameters for the **RdbStore** object based on service requirements and use **RdbStore** APIs to perform data operations.
- **context**: application context.
- **config**: configuration of the RDB store.| +| deleteRdbStore(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: application context.
- **name**: name of the RDB store to delete.| ### Managing Data in an RDB Store @@ -33,29 +33,29 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| + | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating Data** - Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicatesV9**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. + Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. **Table 3** API for updating data - | Class | API | Description | + | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | update(values: ValuesBucket, predicates: RdbPredicatesV9): Promise<number> | Updates data based on the specified **RdbPredicatesV9** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data. | + | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data. | - **Deleting Data** - Call **delete()** to delete the data that meets the conditions specified by **RdbPredicatesV9**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. + Call **delete()** to delete the data that meets 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** API for deleting data - | Class | API | Description | + | Class | API | Description | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | - | RdbStoreV9 | delete(predicates: RdbPredicatesV9): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicatesV9** object. This API uses a promise to return the number of rows updated.
- **predicates**: conditions for deleting data. | + | RdbStore | delete(predicates: RdbPredicates): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.
- **predicates**: conditions for deleting data. | - **Querying Data** @@ -66,50 +66,48 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 5** APIs for querying data - -| Class | API | Description | -| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | query(predicates: RdbPredicatesV9, columns?: Array<string>): Promise<ResultSetV9> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| -| RdbStoreV9 | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSetV9> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| -| RdbStoreV9 | remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicatesV9** that specifies the query conditions.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | Class | API | Description | + | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: 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>): Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicates** that specifies the query condition.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| ### Using Predicates -The **RDB** module provides **RdbPredicatesV9** for you to set database operation conditions. +The **RDB** module provides **RdbPredicates** for you to set database operation conditions. -The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). +The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-relationalStore.md#rdbpredicates). **Table 6** APIs for using RDB store predicates -| Class | API | Description | +| Class | API | Description | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbPredicatesV9 | equalTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | -| RdbPredicatesV9 | notEqualTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | -| RdbPredicatesV9 | or(): RdbPredicatesV9 | Adds the OR condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the OR condition. | -| RdbPredicatesV9 | and(): RdbPredicatesV9 | Adds the AND condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the AND condition. | -| RdbPredicatesV9 | contains(field: string, value: string): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| 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): RdbPredicates | Sets an **RdbPredicates** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| ### Using the Result Set -You can use the APIs provided by **ResultSetV9** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. +You can use the APIs provided by **ResultSet** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. -For details about how to use result set APIs, see [Result Set](../reference/apis/js-apis-data-resultset.md). +For details about how to use **ResultSet** APIs, see [ResultSet](../reference/apis/js-apis-data-relationalStore.md#resultset). -> **NOTICE** -> +> **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 | | ----------- | ---------------------------------------- | ------------------------------------------ | -| ResultSetV9 | goToFirstRow(): boolean | Moves to the first row of the result set. | -| ResultSetV9 | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. | -| ResultSetV9 | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| -| ResultSetV9 | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. | -| ResultSetV9 | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. | -| ResultSetV9 | close(): void | Closes the result set. | +| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set. | +| ResultSet | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. | +| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| +| ResultSet | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. | +| ResultSet | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. | +| ResultSet | close(): void | Closes the result set. | @@ -117,7 +115,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis > **NOTE** > -> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore V9**. +> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore**. > - The devices must be connected over network before the distributed tables are used. For details about the APIs and usage, see [Device Management](../reference/apis/js-apis-device-manager.md). **Setting Distributed Tables** @@ -126,7 +124,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** @@ -136,7 +134,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | 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 required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| +| 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 required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** @@ -144,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: 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**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: 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**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** @@ -152,7 +150,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | 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**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| 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**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** @@ -160,7 +158,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.| +| RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.| ### Backing Up and Restoring an RDB Store @@ -170,7 +168,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| +| RdbStore | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| **Restoring an RDB Store** @@ -178,17 +176,17 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| +| RdbStore | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| -**Transaction** +### Transaction Table 15 Transaction APIs | Class | API | Description | | -------- | ----------------------- | --------------------------------- | -| RdbStoreV9 | beginTransaction(): void | Starts the transaction before executing SQL statements.| -| RdbStoreV9 | commit(): void | Commits the executed SQL statements. | -| RdbStoreV9 | rollBack(): void | Rolls back the SQL statements that have been executed. | +| RdbStore | beginTransaction(): void | Starts the transaction before executing SQL statements.| +| RdbStore | commit(): void | Commits the executed SQL statements. | +| RdbStore | rollBack(): void | Rolls back the SQL statements that have been executed. | ## How to Develop @@ -203,27 +201,27 @@ Table 15 Transaction APIs FA model: ```js - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' let context = featureAbility.getContext() 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_CONFIGV9 = { name: "RdbTest.db", + const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` Stage model: ```ts - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // Obtain the context. - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; let context = null - class MainAbility extends Ability { + class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { context = this.context } @@ -231,10 +229,10 @@ Table 15 Transaction APIs 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_CONFIGV9 = { name: "rdbstore.db", + const STORE_CONFIG = { name: "rdbstore.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` @@ -248,14 +246,29 @@ Table 15 Transaction APIs The sample code is as follows: ```js - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - let insertPromise = rdbStoreV9.insert("test", valueBucket) + let insertPromise = rdbStore.insert("test", valueBucket) + ``` + + ```js + // Use a transaction to insert data. + beginTransaction() + try { + let u8 = new Uint8Array([1, 2, 3]) + const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } + const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 } + let insertPromise1 = rdbStore.insert("test", valueBucket1) + let insertPromise2 = rdbStore.insert("test", valueBucket2) + commit() + } catch (e) { + rollBack() + } ``` 3. Query data. - (1) Create an **RdbPredicatesV9** object to specify query conditions. + (1) Create an **RdbPredicates** object to specify query conditions. (2) Call the **query()** API to query data. @@ -264,17 +277,17 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let predicatesV9 = new data_rdb.RdbPredicatesV9("test"); - predicatesV9.equalTo("name", "Tom") - let promisequery = rdbStoreV9.query(predicatesV9) - promisequery.then((resultSetV9) => { - resultSetV9.goToFirstRow() - const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id")) - const name = resultSetV9.getString(resultSetV9.getColumnIndex("name")) - const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age")) - const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary")) - const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType")) - resultSetV9.close() + let predicates = new data_rdb.RdbPredicates("test"); + predicates.equalTo("name", "Tom") + let promisequery = rdbStore.query(predicates) + promisequery.then((resultSet) => { + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("id")) + const name = resultSet.getString(resultSet.getColumnIndex("name")) + const age = resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) + resultSet.close() }) ``` @@ -302,7 +315,7 @@ Table 15 Transaction APIs context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { console.info(`result.requestCode=${result.requestCode}`) }) - let promise = rdbStoreV9.setDistributedTables(["test"]) + let promise = rdbStore.setDistributedTables(["test"]) promise.then(() => { console.info("setDistributedTables success.") }).catch((err) => { @@ -312,7 +325,7 @@ Table 15 Transaction APIs 5. Synchronize data across devices. - (1) Construct an **RdbPredicatesV9** object to specify remote devices within the network to be synchronized. + (1) Construct an **RdbPredicates** object to specify remote devices within the network to be synchronized. (2) Call **rdbStore.sync()** to synchronize data. @@ -321,9 +334,9 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let predicateV9 = new data_rdb.RdbPredicatesV9('test') - predicateV9.inDevices(['12345678abcde']) - let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicateV9) + let predicate = new data_rdb.RdbPredicates('test') + predicate.inDevices(['12345678abcde']) + let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) promise.then((result) => { console.log('sync done.') for (let i = 0; i < result.length; i++) { @@ -350,7 +363,7 @@ Table 15 Transaction APIs } try { - rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { console.log('register observer failed') } @@ -365,8 +378,8 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let tableName = rdbStoreV9.obtainDistributedTableName(deviceId, "test"); - let resultSetV9 = rdbStoreV9.querySql("SELECT * FROM " + tableName) + let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); + let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` 8. Query data of a remote device. @@ -379,17 +392,17 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let rdbPredicateV9 = new data_rdb.RdbPredicatesV9('employee') - predicatesV9.greaterThan("id", 0) - let promiseQuery = rdbStoreV9.remoteQuery('12345678abcde', 'employee', rdbPredicateV9) - promiseQuery.then((resultSetV9) => { - while (resultSetV9.goToNextRow()) { - let idx = resultSetV9.getLong(0); - let name = resultSetV9.getString(1); - let age = resultSetV9.getLong(2); + let rdbPredicate = new data_rdb.RdbPredicates('employee') + predicates.greaterThan("id", 0) + let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) + promiseQuery.then((resultSet) => { + while (resultSet.goToNextRow()) { + let idx = resultSet.getLong(0); + let name = resultSet.getString(1); + let age = resultSet.getLong(2); console.info(idx + " " + name + " " + age); } - resultSetV9.close(); + resultSet.close(); }).catch((err) => { console.info("failed to remoteQuery, err: " + err) }) @@ -402,7 +415,7 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let promiseBackup = rdbStoreV9.backup("dbBackup.db") + let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(() => { console.info('Backup success.') }).catch((err) => { @@ -414,7 +427,7 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let promiseRestore = rdbStoreV9.restore("dbBackup.db") + let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(() => { console.info('Restore success.') }).catch((err) => { diff --git a/en/application-dev/device/inputdevice-guidelines.md b/en/application-dev/device/inputdevice-guidelines.md index d29d1ae340f5f2c569559791fe2b001e07adce4a..da6eef71d750b74e01d1ea8a9eaaf49b1bf598cb 100644 --- a/en/application-dev/device/inputdevice-guidelines.md +++ b/en/application-dev/device/inputdevice-guidelines.md @@ -16,8 +16,8 @@ The following table lists the common APIs for input device management. For detai | Instance| API | Description| | ----------- | ------------------------------------------------------------ | -------------------------- | -| inputDevice | function getDeviceList(callback: AsyncCallback\>): void; | Obtains the list of input devices.| -| inputDevice | function getKeyboardType(deviceId: number, callback: AsyncCallback\): void; | Obtains the keyboard type of the input device.| +| inputDevice | function getDeviceList(): Promise\>; | Obtains the list of input devices.| +| inputDevice | function getKeyboardType(deviceId: number): Promise\; | Obtains the keyboard type of the input device.| | inputDevice | function on(type: "change", listener: Callback\): void; | Enables listening for device hot swap events.| | inputDevice | function off(type: "change", listener?: Callback\): void; | Disables listening for device hot swap events.| @@ -51,7 +51,7 @@ try { // 2. Listen for device hot swap events. inputDevice.on("change", (data) => { console.log(`Device event info: ${JSON.stringify(data)}`); - inputDevice.getKeyboardType(data.deviceId, (error, type) => { + inputDevice.getKeyboardType(data.deviceId).then((type) => { console.log("The keyboard type is: " + type); if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { // The physical keyboard is inserted. diff --git a/en/application-dev/notification/Readme-EN.md b/en/application-dev/notification/Readme-EN.md index dccfc8dbc4c59611db4aa53ff8a5a295cbba4d46..bf85581053f30d6aa56e0218c51339ef6ee3f268 100644 --- a/en/application-dev/notification/Readme-EN.md +++ b/en/application-dev/notification/Readme-EN.md @@ -1,9 +1,10 @@ -# Common Event and Notification +# Notification + +- [Notification Overview](notification-overview.md) +- [Notification Subscription (Open Only to System Applications)](notification-subscription.md) +- [Enabling Notification](notification-enable.md) +- Publishing a Notification + - [Publishing a Basic Notification](text-notification.md) + - [Publishing a Progress Notification](progress-bar-notification.md) + - [Adding a WantAgent Object to a Notification](notification-with-wantagent.md) -- [Common Event and Notification Overview](notification-brief.md) -- [Common Event Development](common-event.md) -- [Notification Development](notification-guidelines.md) -- Agent-Powered Scheduled Reminder - - [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md) - - [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md) -- [Debugging Assistant Usage](assistant-guidelines.md) diff --git a/en/application-dev/notification/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md deleted file mode 100644 index 5d83cf443c0f629fcb471a6c12ccd3069ac2e593..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/assistant-guidelines.md +++ /dev/null @@ -1,134 +0,0 @@ -# Debugging Assistant Usage - -The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell. - -## cem Debugging Assistant - -### publish - -* Function - - Publishes a common event. - -* Usage - - `cem publish []` - - The table below describes the available options. - - | Option | Description | - | ------------ | ------------------------------------------ | - | -e/--event | Indicates the name of the common event to publish. Mandatory. | - | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published. | - | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | - | -c/--code | Indicates the result code of the common event. Optional. | - | -d/--data | Indicates the data carried in the common event. Optional. | - | -h/--help | Indicates the help Information | - -* Example - - `cem publish --event "testevent"` - - Publish a common event named **testevent**. - - ![cem-publish-event](figures/cem-publish-event.png) - - - - `cem publish -e "testevent" -s -o -c 100 -d "this is data" ` - - Publish a sticky, ordered common event named **testevent**. The result code of the event is **100** and the data carried is **this is data**. - - ![cem-publish-all](figures/cem-publish-all.png) - -### dump - -* Function - - Displays information about common events. - -* Usage - - `cem dump []` - - The table below describes the available options. - - | Option | Description | - | ---------- | -------------------------------------------- | - | -a/--all | Displays information about all common events that have been sent since system startup. | - | -e/--event | Displays information about a specific event. | - | -h/--help | Displays the help information. | - -* Example - -​ `cem dump -e "testevent"` - -​ Display information about the common event testevent. - -​ ![cem-dump-e](figures/cem-dump-e.png) - -### help - -* Function - - Displays the help information. - -* Usage - - `cem help` - -* Example - - ![cem-help](figures/cem-help.png) - - - -## anm Debugging Assistant - -### dump - -* Function - - Displays information about notifications. - -* Usage - - `anm dump []` - - The table below describes the available options. - - | Option | Description | - | ---------------- | ---------------------------------------- | - | -A/--active | Displays information about all active notifications. | - | -R/--recent | Displays information about the recent notifications. | - | -D/--distributed | Displays information about distributed notifications from other devices. | - | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional. | - | -h/--help | Displays the help information. | - -* Example - - `anm dump -A` - - Display information about all active notifications. - - ![anm-dump-A](figures/anm-dump-A.png) - - - - `anm dump --setRecentCount 10` - - Set the number of the cached recent notifications to be displayed to **10**. - -### help - -* Function - - Displays the help information. - -* Usage - - `anm help` - -* Example - - ![anm-help](figures/anm-help.png) diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md deleted file mode 100644 index dfb611ea572b80486756faaa4b004513cd6858a7..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/common-event.md +++ /dev/null @@ -1,172 +0,0 @@ -# Common Event Development -## Introduction -OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. - -Common events are classified into system common events and custom common events. - -+ System common events: The system sends an event based on system policies to the apps that have subscribed to this event when it occurs. This type of event is typically system events published by key system services, such as HAP installation, update, and uninstallation. - -+ Custom common event: customized by applications to implement cross-application event communication. - -Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application. - -## Common Event Subscription Development - -### When to Use -You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#support). - -### Available APIs -| API | Description| -| ---------------------------------------------------------------------------------------------- | ----------- | -| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| -| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | -| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| - -### How to Develop -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). - -```js -// Used to save the created subscriber object for subsequent subscription and unsubscription. -private subscriber = null - -// Subscriber information -var subscribeInfo = { - events: ["event"], -} -``` - -3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. - -```js -// Callback for subscriber creation. -commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { - if (err.code) { - console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]CreateSubscriber") - this.subscriber = subscriber - this.result = "Create subscriber succeed" - } -}) -``` - -4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). - -```js -// Callback for common event subscription. -if (this.subscriber != null) { - commonEvent.subscribe(this.subscriber, (err, data) => { - if (err.code) { - console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data)) - this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code - } - }) - this.result = "Subscribe succeed" -} else { - prompt.showToast({ message: "Need create subscriber" }) -} -``` - -## Common Event Publishing Development - -### When to Use -You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. - -### Available APIs -| API | Description| -| ---------------------------------- | ------ | -| publish(event: string, callback: AsyncCallback) | Publishes a common event.| -| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| - -### How to Develop -#### Development for Publishing a Common Event -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Pass in the common event name and callback, and publish the event. - -```js -// Publish a common event. -commonEvent.publish("event", (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish1") - } -}) -``` - -#### Development for Publishing a Common Event with Given Attributes -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent' -``` - -2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). - -```js -// Attributes of a common event. -var options = { - code: 1, // Result code of the common event - data: "initial data";// Result data of the common event -} -``` - -3. Pass in the common event name, attributes of the common event, and callback, and publish the event. - -```js -// Publish a common event. -commonEvent.publish("event", options, (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish2") - } -}) -``` - -## Common Event Unsubscription Development - -### When to Use -You can use the **unsubscribe** API to unsubscribe from a common event. - -### Available APIs -| API | Description| -| ---------------------------------- | ------ | -| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| - -### How to Develop -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#common-event-subscription-development). -3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. - -```js -if (this.subscriber != null) { - commonEvent.unsubscribe(this.subscriber, (err) => { - if (err.code) { - console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]Unsubscribe") - this.subscriber = null - this.result = "Unsubscribe succeed" - } - }) -} -``` diff --git a/en/application-dev/notification/figures/anm-dump-A.png b/en/application-dev/notification/figures/anm-dump-A.png deleted file mode 100644 index 368e6f2d810976486e786a4c8f0603a87ad48540..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/anm-dump-A.png and /dev/null differ diff --git a/en/application-dev/notification/figures/anm-help.png b/en/application-dev/notification/figures/anm-help.png deleted file mode 100644 index d80ac8e76a70c2be383f0a05a12e3e707dcf242b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/anm-help.png and /dev/null differ diff --git a/en/application-dev/notification/figures/ans.png b/en/application-dev/notification/figures/ans.png deleted file mode 100644 index 8be552d2acedbef962326365fb2d19ded3838c14..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/ans.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-dump-e.png b/en/application-dev/notification/figures/cem-dump-e.png deleted file mode 100644 index c2422ba0e51011174c333985ad7647f170e0f126..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-dump-e.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-help.png b/en/application-dev/notification/figures/cem-help.png deleted file mode 100644 index 8ca4bc0605f9c1f75a8cb45f8ab77c9c5d6f04e4..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-help.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-publish-all.png b/en/application-dev/notification/figures/cem-publish-all.png deleted file mode 100644 index 99526e1f7245d101914354e2a89d5e97d710c27f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-publish-all.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-publish-event.png b/en/application-dev/notification/figures/cem-publish-event.png deleted file mode 100644 index f0ca7e73093f1be72c743bd7c08467f11e2a0e05..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-publish-event.png and /dev/null differ diff --git a/en/application-dev/notification/figures/ces.png b/en/application-dev/notification/figures/ces.png deleted file mode 100644 index b1aa5438a19ac79899e0f45791f3e1a79e4242dc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/ces.png and /dev/null differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001416585590.png b/en/application-dev/notification/figures/en-us_image_0000001416585590.png new file mode 100644 index 0000000000000000000000000000000000000000..9da6812580fd6c7d785391c652104ef0698ce2bc Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416585590.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001416745530.png b/en/application-dev/notification/figures/en-us_image_0000001416745530.png new file mode 100644 index 0000000000000000000000000000000000000000..7a6fd0d9304abef2eb240a3c78a93b73bb9237af Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416745530.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062434.png b/en/application-dev/notification/figures/en-us_image_0000001417062434.png new file mode 100644 index 0000000000000000000000000000000000000000..07db3298f0db1c3357624b44d271dc1e6f97ea9e Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062434.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062446.png b/en/application-dev/notification/figures/en-us_image_0000001417062446.png new file mode 100644 index 0000000000000000000000000000000000000000..c197fd6293f41890b2bfcf17a28a1477e8aa6d96 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062446.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462297.png b/en/application-dev/notification/figures/en-us_image_0000001466462297.png new file mode 100644 index 0000000000000000000000000000000000000000..a07d9e818677e9364ad3239e61ce198471b68603 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462297.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462305.png b/en/application-dev/notification/figures/en-us_image_0000001466462305.png new file mode 100644 index 0000000000000000000000000000000000000000..740f4b79a9ee234008cad6cf3616a8f213569476 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462305.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582017.png b/en/application-dev/notification/figures/en-us_image_0000001466582017.png new file mode 100644 index 0000000000000000000000000000000000000000..1652d9111be2a27863fe2322c4feb577bab22ae9 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582017.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582045.png b/en/application-dev/notification/figures/en-us_image_0000001466582045.png new file mode 100644 index 0000000000000000000000000000000000000000..4040452a87bc69ae8fa0eb9b55ca77ac32bdb2d8 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582045.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782025.png b/en/application-dev/notification/figures/en-us_image_0000001466782025.png new file mode 100644 index 0000000000000000000000000000000000000000..d8e45c1746ab419a8056f9493c8796cfb734d2d0 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782025.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782033.png b/en/application-dev/notification/figures/en-us_image_0000001466782033.png new file mode 100644 index 0000000000000000000000000000000000000000..218e5fcef6d163113c9037028215297ef626fcfa Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782033.png differ diff --git a/en/application-dev/notification/figures/notification-with-wantagent.png b/en/application-dev/notification/figures/notification-with-wantagent.png new file mode 100644 index 0000000000000000000000000000000000000000..234ef895c918404598cf7640f9d072de2bb2d0d0 Binary files /dev/null and b/en/application-dev/notification/figures/notification-with-wantagent.png differ diff --git a/en/application-dev/notification/figures/notification.png b/en/application-dev/notification/figures/notification.png deleted file mode 100644 index 18dcb99b0c531a19698f749105d88db91043837a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/notification.png and /dev/null differ diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md deleted file mode 100644 index 75237412fdf29d88843a9f23fa653f64f2de7c86..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/notification-brief.md +++ /dev/null @@ -1,20 +0,0 @@ -# Common Event and Notification Overview - -The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more. - -Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. - -![ces](figures/ces.png) - -- System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events. -- Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications. - -The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: - -- Display received SMS messages and instant messages. -- Display push messages of applications, such as advertisements, version updates, and news notifications. -- Display ongoing events, such as music playback, navigation information, and download progress. - -Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions. - -![ans](figures/ans.png) diff --git a/en/application-dev/notification/notification-enable.md b/en/application-dev/notification/notification-enable.md new file mode 100644 index 0000000000000000000000000000000000000000..12aa4f41eb1570d707b4c65310cefe6aa45e1b17 --- /dev/null +++ b/en/application-dev/notification/notification-enable.md @@ -0,0 +1,49 @@ +# Enabling Notification + + +To publish a notification, you must have notification enabled for your application. You can call the [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) API to display a dialog box prompting the user to enable notification for your application. Note that the dialog box is displayed only when the API is called for the first time. + + **Figure 1** Dialog box prompting the user to enable notification + +![en-us_image_0000001416585590](figures/en-us_image_0000001416585590.png) + + +- Touching **allow** enables notification for the application, and touching **ban** keeps notification disabled. + +- The dialog box will not be displayed again when [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) is called later. The user can manually enable notification as follows. + + | 1. Swipe down from the upper left corner of the device screen to access the notification panel. | 2. Touch the **Settings** icon in the upper right corner. On the notification screen, locate the target application.| 3. Toggle on **Allow notifications**. | + | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | + | ![en-us_image_0000001417062434](figures/en-us_image_0000001417062434.png) | ![en-us_image_0000001466462297](figures/en-us_image_0000001466462297.png) | ![en-us_image_0000001466782025](figures/en-us_image_0000001466782025.png) | + + +## Available APIs + +For details about the APIs, see [@ohos.notificationManager](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification). + +**Table 1** Notification APIs + +| Name | Description | +| -------- | -------- | +| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback<boolean>): void | Checks whether notification is enabled.
**NOTE**
This is a system API and cannot be called by third-party applications. | +| setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback<void>): void | Sets whether to enable notification. Notification can be enabled or disabled in **Notifications** of the target application under **Settings** > **Apps & services** > **Apps**.
**NOTE**
This is a system API and cannot be called by third-party applications.| +| requestEnableNotification(callback: AsyncCallback<void>): void | Requests notification to be enabled. When called for the first time, this API displays a dialog box prompting the user to enable notification. | + + +## How to Develop + +1. Import the **NotificationManager** module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +2. Call the API to request notification to be enabled. + + ```ts + notificationManager.requestEnableNotification().then(() => { + console.info(`[ANS] requestEnableNotification success`); + }).catch((err) => { + console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`); + }); + ``` diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md deleted file mode 100644 index fb73f274202aafd9ff852201ca2fb8c5116aba50..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/notification-guidelines.md +++ /dev/null @@ -1,258 +0,0 @@ - - -# Notification Development - -## When to Use - -OpenHarmony uses the Advanced Notification Service (ANS) to manage notifications, with support for various notification types, including text, long text, multi-text, image, social, and media. All system services and applications can send notifications through the notification API. Users can view all notifications on the system UI. - -Below are some typical use cases for notifications: - -- Display received SMS messages and instant messages. -- Display push messages of applications, such as advertisements and version updates. -- Display ongoing events, such as navigation information and download progress. - - - -## Notification Service Process - -The notification service process involves the ANS subsystem, notification sender, and notification subscriber. - -A notification is generated by the notification sender and sent to the ANS through inter-process communication (IPC). The ANS then distributes the notification to the notification subscriber. - -System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the ANS for storage in the memory and database. - -![1648113187545](figures/notification.png) - - - -## Available APIs - -Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md). - -**Table 1** APIs for notification enabling - -| API | Description | -| ------------------------------------------------------------ | ---------------- | -| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.| -| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. | - -If the notification function of an application is disabled, it cannot send notifications. - - - -**Table 2** APIs for notification subscription - -| API | Description | -| ------------------------------------------------------------ | ---------------- | -| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void | Subscribes to a notification with the subscription information specified.| -| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Subscribes to all notifications. | -| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Unsubscribes from a notification. | - -The subscription APIs support subscription to all notifications and notifications from specific applications. - - - -**Table 3** Notification subscription callbacks - -| API | Description | -| ------------------------------------------------ | ---------------- | -| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | -| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | -| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.| -| onConnect?:() => void; | Callback for subscription. | -| onDisconnect?:() => void; | Callback for unsubscription. | - - - -**Table 4** APIs for notification sending - -| API | Description | -| ------------------------------------------------------------ | ------------------------ | -| publish(request: NotificationRequest, callback: AsyncCallback\): void | Publishes a notification. | -| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void | Publishes a notification to the specified user. | -| cancel(id: number, label: string, callback: AsyncCallback\): void | Cancels a specified notification. | -| cancelAll(callback: AsyncCallback\): void; | Cancels all notifications published by the application.| - -The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. - - - -## Development Guidelines - -The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications. - -### Modules to Import - -```js -import Notification from '@ohos.notification'; -``` - - - -### Subscribing to Notifications - -The notification recipient preferentially initiates a notification subscription request to the notification subsystem. - -```js -var subscriber = { - onConsume: function (data) { - let req = data.request; - console.info('===>onConsume callback req.id: ' + req.id); - }, - onCancel: function (data) { - let req = data.request; - console.info('===>onCancel callback req.id: : ' + req.id); - }, - onUpdate: function (data) { - console.info('===>onUpdate in test===>'); - }, - onConnect: function () { - console.info('===>onConnect in test===>'); - }, - onDisconnect: function () { - console.info('===>onDisConnect in test===>'); - }, - onDestroy: function () { - console.info('===>onDestroy in test===>'); - }, - }; - - Notification.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. - if (err.code) { - console.error('===>failed to subscribe because ' + JSON.stringify(err)); - return; - } - console.info('===>subscribeTest success : ' + JSON.stringify(data)); - }); -``` - - - -### Publishing Notifications - -##### Enabling Notification - -Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature. - -```js -Notification.requestEnableNotification().then((data) => { - console.info('===>requestEnableNotification success'); -}).catch((err) => { - console.error('===>requestEnableNotification failed because ' + JSON.stringify(err)); -}); -``` - - - -##### Publishing Notifications - -To publish a notification, create a **NotificationRequest** object and set attributes such as the notification type, title, and content. In the following examples, a normal text notification and a notification containing a **WantAgent** are being published. - -Normal text notification: - -```js -// Create a NotificationRequest object. -var notificationRequest = { - id: 1, - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "test_title", - text: "test_text", - additionalText: "test_additionalText" - } - } -} - -// Publish the notification. -Notification.publish(notificationRequest).then((data) => { - console.info('===>publish promise success req.id : ' + notificationRequest.id); -}).catch((err) => { - console.error('===>publish promise failed because ' + JSON.stringify(err)); -}); -``` - - - -Notification containing **WantAgent**: - -For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md). - -- Create a **WantAgent** object. - -```js -import wantAgent from '@ohos.wantAgent'; - -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - bundleName: 'ohos.samples.eTSNotification', - abilityName: 'ohos.samples.eTSNotification.MainAbility', - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -// WantAgent object -var WantAgent; - -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("===>getWantAgentCallback===>"); - if (err.code == 0) { - WantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} - -// Obtain the WantAgent object. -wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) -``` - -- Publish the notification. - -```js -// Create a NotificationRequest object. -var notificationRequest = { - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "AceApplication_Title", - text: "AceApplication_Text", - additionalText: "AceApplication_AdditionalText" - }, - }, - id: 1, - label: 'TEST', - wantAgent: WantAgent, - slotType: Notification.SlotType.OTHER_TYPES, - deliveryTime: new Date().getTime() -} - -// Publish the notification. -Notification.publish(notificationRequest).then((data) => { - console.info('===>publish promise success req.id : ' + notificationRequest.id); -}).catch((err) => { - console.error('===>publish promise failed because ' + JSON.stringify(err)); -}); -``` - - - -- Cancel the notification. - -An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself. - -```js -// cancel callback -function cancelCallback(err) { - console.info("===>cancelCallback===>"); -} - -Notification.cancel(1, "label", cancelCallback) -``` diff --git a/en/application-dev/notification/notification-overview.md b/en/application-dev/notification/notification-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6bef8be8fd446e62b3e3da04582b467c9ddc5961 --- /dev/null +++ b/en/application-dev/notification/notification-overview.md @@ -0,0 +1,27 @@ +# Notification Overview + + +## Introduction + +All system applications and services can publish notifications through the notification APIs. Users can view the notifications in the notification panel or click a notification to open the publishing application. + +Below are some typical use cases for notifications: + +- Display received SMS messages and instant messages. + +- Display push messages, such as advertisements and version updates. + +- Display ongoing events, such as the download progress. + +The Advanced Notification Service (ANS) in OpenHarmony is used to manage notifications of various types, such as basic notifications, progress notifications, and reminders published through the background agent. + + +## Notification Service Process + +The notification service process involves the notification subsystem, notification sender, and notification subscriber. + +A notification is generated by the notification sender and sent to the notification subsystem through [inter-process communication (IPC)](../connectivity/ipc-rpc-overview.md). The notification subsystem then distributes the notification to the notification subscriber. + +System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the notification subsystem for storage in the memory and database. + +![en-us_image_0000001466582017](figures/en-us_image_0000001466582017.png) diff --git a/en/application-dev/notification/notification-subscription.md b/en/application-dev/notification/notification-subscription.md new file mode 100644 index 0000000000000000000000000000000000000000..a633a2bb955bcf877fbe4befb8b40ad103d7e7e6 --- /dev/null +++ b/en/application-dev/notification/notification-subscription.md @@ -0,0 +1,82 @@ +# Notification Subscription (Open Only to System Applications) + + +To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application. + + +You can use the **NotificationSubscriber** object to provide callbacks for subscription events, such as subscription success, notification reception, notification cancellation, and subscription cancellation. + + +## Available APIs + +The major APIs for notification subscription are described as follows. For details about the APIs, see [@ohos.notificationSubscribe](../reference/apis/js-apis-notificationSubscribe.md). + +**Table 1** Major APIs for notification subscription + +| Name | Description| +| -------- | -------- | +| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback<void>): void | Subscribes to notifications from a specific application.| +| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Subscribes to notifications from all applications. | + +**Table 2** Callbacks for notification subscription + +| Name | Description| +| -------- | -------- | +| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | +| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | +| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates. | +| onConnect?:() => void; | Callback for subscription. | +| onDisconnect?:() => void; | Callback for unsubscription. | +| onDestroy?:() => void | Callback for disconnecting from the notification subsystem. | +| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) => void | Callback for the Do Not Disturb (DNT) time changes.| +| onEnabledNotificationChanged?:(callbackData: EnabledNotificationCallbackData) => void | Callback for notification switch changes. | + + +## How to Develop + +1. Request the **ohos.permission.NOTIFICATION_CONTROLLER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Import the **notificationSubscribe** module. + + ```ts + import notificationSubscribe from '@ohos.notificationSubscribe'; + ``` + +3. Create a **subscriber** object. + + ```ts + let subscriber = { + onConsume: function (data) { + let req = data.request; + console.info('[ANS] onConsume callback req.id: ' + req.id); + }, + onCancel: function (data) { + let req = data.request; + console.info('[ANS] onCancel callback req.id: : ' + req.id); + }, + onUpdate: function (data) { + console.info('[ANS] onUpdate in test'); + }, + onConnect: function () { + console.info('[ANS] onConnect in test'); + }, + onDisconnect: function () { + console.info('[ANS] onDisConnect in test'); + }, + onDestroy: function () { + console.info('[ANS] onDestroy in test'); + }, + }; + ``` + +4. Initiate notification subscription. + + ```ts + notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. + if (err) { + console.error(`[ANS] failed to subscribe, error[${err}]`); + return; + } + console.info(`[ANS] subscribeTest success : + ${data}`); + }); + ``` diff --git a/en/application-dev/notification/notification-with-wantagent.md b/en/application-dev/notification/notification-with-wantagent.md new file mode 100644 index 0000000000000000000000000000000000000000..d8f0321d28738749d6ed6073e49f26181c22e706 --- /dev/null +++ b/en/application-dev/notification/notification-with-wantagent.md @@ -0,0 +1,121 @@ +# Adding a WantAgent Object to a Notification + +A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsulates an intention to start a specified ability, release a common event, and more. In OpenHarmony, a **WantAgent** object can be passed in a notification from the publisher to the subscriber, so as to trigger the intention specified. For example, you may want the user to start a specific ability by touching the notification published by your application. In this case, you can add a **WantAgent** object that encapsulates such an action to the notification. After receiving the **WantAgent** object, the system triggers it once the user touches the notification from the notification panel, starting the specified ability. + +Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered. + + **Figure 1** Publishing a notification with a WantAgent object +![notification-with-wantagent](figures/notification-with-wantagent.png) + + +## Available APIs + +For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). + +| Name| Description| +| -------- | -------- | +| getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void | Creates a **WantAgent** object.| +| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void | Triggers a **WantAgent** object.| +| cancel(agent: WantAgent, callback: AsyncCallback<void>): void | Cancels a **WantAgent** object.| +| getWant(agent: WantAgent, callback: AsyncCallback<Want>): void | Obtains a **WantAgent** object.| +| equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void | Checks whether two **WantAgent** objects are equal. | + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the modules. + + ```typescript + import notificationManager from '@ohos.notificationManager'; + import wantAgent from '@ohos.app.ability.wantAgent'; + ``` + +3. Create a **WantAgentInfo** object. + + Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component. + + ```typescript + let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations. + + // Set the action type through operationType of WantAgentInfo. + let wantAgentInfo = { + wants: [ + { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: '', + entities: [], + uri: '', + parameters: {} + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] + }; + ``` + + Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md). + + ```typescript + let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations. + + // Set the action type through operationType of WantAgentInfo. + let wantAgentInfo = { + wants: [ + { + action: 'event_name', // Set the action name. + parameters: {}, + } + ], + operationType: wantAgent.OperationType.SEND_COMMON_EVENT, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], + } + ``` + +4. Invoke the [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) API to create a **WantAgent** object. + + ```typescript + // Create a WantAgent object. + wantAgent.getWantAgent(wantAgentInfo, (err, data) => { + if (err) { + console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err)); + return; + } + console.info('[WantAgent]getWantAgent success'); + wantAgentObj = data; + }); + ``` + +5. Create a **NotificationRequest** object and publish a notification that carries the **WantAgent** object. + + ```typescript + // Create a NotificationRequest object. + let notificationRequest = { + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: 'Test_Title', + text: 'Test_Text', + additionalText: 'Test_AdditionalText', + }, + }, + id: 1, + label: 'TEST', + wantAgent: wantAgentObj, + } + + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + +6. When the user touches the notification from the notification panel, the system automatically triggers the action specified in the **WantAgent** object. diff --git a/en/application-dev/notification/progress-bar-notification.md b/en/application-dev/notification/progress-bar-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..de430008e3048532e9afea94d83a62dd2f8342c1 --- /dev/null +++ b/en/application-dev/notification/progress-bar-notification.md @@ -0,0 +1,69 @@ +# Publishing a Progress Notification + + +The progress notification is a commonly used notification type, mainly used to display the progress of an ongoing operation, such as file downloading. When publishing a progress notification through the notification subsystem, you can use the readily available template by specifying the related attributes, such as the template name and template data. + +In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data. + + +## Available APIs + +| Name| Description| +| -------- | -------- | +| isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result.
Only the progress-type template is supported.| + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +3. Check whether a specific template is supported. In this example, the template of the **downloadTemplate** type is checked. + + ```ts + notificationManager.isSupportTemplate('downloadTemplate').then((data) => { + console.info(`[ANS] isSupportTemplate success`); + let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite. + // ... + }).catch((err) => { + console.error(`[ANS] isSupportTemplate failed, error[${err}]`); + }); + ``` + + > **NOTE** + > + > Proceed with the step below only when the specified template is supported. +4. Create a **NotificationRequest** object and publish a progress notification. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText' + } + }, + // Create a progress template. The name field has a fixed value of downloadTemplate. + template: { + name: 'downloadTemplate', + data: { title: 'File Title', fileName: 'music.mp4', progressValue: 45 } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success `); + }); + ``` diff --git a/en/application-dev/notification/text-notification.md b/en/application-dev/notification/text-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..ddbc5478cee37208da33d2acecb71417deaccdc2 --- /dev/null +++ b/en/application-dev/notification/text-notification.md @@ -0,0 +1,160 @@ +# Publishing a Basic Notification + + +You can publish basic notifications to send SMS messages, prompt messages, and advertisements. Available content types of basic notifications include normal text, long text, multi-line text, and picture-attached. + + + **Table 1** Basic notification content types + +| Type| Description| +| -------- | -------- | +| NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification.| +| NOTIFICATION_CONTENT_LONG_TEXT | Long text notification.| +| NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| +| NOTIFICATION_CONTENT_PICTURE | Picture-attached notification.| + + +Notifications are displayed in the notification panel, which is the only system subscriber to notifications. Below you can see two examples of the basic notification. + +**Figure 1** Examples of the basic notification +![en-us_image_0000001466462305](figures/en-us_image_0000001466462305.png) + + +## Available APIs + +The following table describes the APIs for notification publishing. You specify the notification type by setting the [NotificationRequest](../reference/apis/js-apis-notificationManager.md#notificationrequest) parameter in the APIs. + +| Name| Description| +| -------- | -------- | +| publish(request: NotificationRequest, callback: AsyncCallback<void>): void | Publishes a notification. | +| cancel(id: number, label: string, callback: AsyncCallback<void>): void | Cancels a notification. | +| cancelAll(callback: AsyncCallback<void>): void; | Cancels all notifications published by the application.| + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +3. Create a **NotificationRequest** object and publish a progress notification. + - A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification + normal: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + } + } + } + + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the normal text notification. + ![en-us_image_0000001466782033](figures/en-us_image_0000001466782033.png) + - In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification + longText: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + longText: 'test_longText', + briefText: 'test_briefText', + expandedTitle: 'test_expandedTitle', + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the long-text notification. + ![en-us_image_0000001416745530](figures/en-us_image_0000001416745530.png) + - In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification + multiLine: { + title: 'test_title', + text: 'test_text', + briefText: 'test_briefText', + longTitle: 'test_longTitle', + lines: ['line_01', 'line_02', 'line_03', 'line_04'], + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the multi-line notification. + ![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png) + - In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB. + + ```ts + let notificationPicture: PixelMap = undefined; // Obtain the pixel map information. + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE, + picture: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + briefText: 'test_briefText', + expandedTitle: 'test_expandedTitle', + picture: notificationPicture + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success `); + }); + ``` + + Below is an example of the picture-attached notification. + ![en-us_image_0000001466582045](figures/en-us_image_0000001466582045.png) diff --git a/en/application-dev/quick-start/figures/02.png b/en/application-dev/quick-start/figures/02.png index 19dd76ca232282b19883dde63075c5d155e7db70..eef374a1fd63f2b1e4d72e3323e7f4c23f5705fb 100644 Binary files a/en/application-dev/quick-start/figures/02.png and b/en/application-dev/quick-start/figures/02.png differ diff --git a/en/application-dev/quick-start/figures/04.png b/en/application-dev/quick-start/figures/04.png index cf23d17c7ee8552e30a5b234c97862b51981dcf8..1190d1e5aa631b12171632d258e4c4fae32e9bba 100644 Binary files a/en/application-dev/quick-start/figures/04.png and b/en/application-dev/quick-start/figures/04.png differ diff --git a/en/application-dev/quick-start/figures/07.png b/en/application-dev/quick-start/figures/07.png index 0f34d01d824ae1780c73cade9a39fff5f4b9b84e..17f2b060d300667ff250935b6a37485843e854ce 100644 Binary files a/en/application-dev/quick-start/figures/07.png and b/en/application-dev/quick-start/figures/07.png differ diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 105928883e9ce6dd263cb9c52e67d8fd9855e5c2..80d0336aa005712ce116d5eb131ab299c1bff006 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -194,23 +194,24 @@ - [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - Security - - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - - [@ohos.privacyManager](js-apis-privacyManager.md) - - [@ohos.security.cryptoFramework](js-apis-cryptoFramework.md) - - [@ohos.security.huks ](js-apis-huks.md) - - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) - - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - - [@system.cipher](js-apis-system-cipher.md) + - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) + - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) + - [@ohos.security.cert (Certificate)](js-apis-cert.md) + - [@ohos.security.cryptoFramework (Crypto Framework)](js-apis-cryptoFramework.md) + - [@ohos.security.huks (HUKS)](js-apis-huks.md) + - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) + - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) + - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - Data Management - - [@ohos.data.dataAbility ](js-apis-data-ability.md) - - [@ohos.data.dataShare](js-apis-data-dataShare.md) - - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - - [@ohos.data.preferences](js-apis-data-preferences.md) - - [@ohos.data.rdb](js-apis-data-rdb.md) - - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md) + - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) + - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) + - [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md) + - [@ohos.data.dataShareResultSet (DataShare Result Set)](js-apis-data-DataShareResultSet.md) + - [@ohos.data.distributedDataObject (Distributed Data Object)](js-apis-data-distributedobject.md) + - [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md) + - [@ohos.data.preferences (Preferences)](js-apis-data-preferences.md) + - [@ohos.data.rdb (RDB)](js-apis-data-rdb.md) + - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - data/rdb - [resultSet](js-apis-data-resultset.md) - File Management @@ -307,6 +308,7 @@ - [@ohos.sensor](js-apis-sensor.md) - [@ohos.settings](js-apis-settings.md) - [@ohos.stationary](js-apis-stationary.md) + - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md) - [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - [@ohos.thermal](js-apis-thermal.md) - [@ohos.update](js-apis-update.md) @@ -324,7 +326,7 @@ - [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md) - Language Base Class Library - - [@ohos.buffer](js-apis-buffer.md) + - [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.process](js-apis-process.md) - [@ohos.uri](js-apis-uri.md) diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index d593cf5a61697773be5837287f0e63d33cff3ce8..ed59083949a8d151e7e007e9b2475d20e91446e6 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -1,4 +1,4 @@ -# Ability Access Control +# @ohos.abilityAccessCtrl (Ability Access Control) The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index 80c507b83ab0012aafbdc9745810730a54997293..6f512b4f9f32904106f9120ea2fcc1095ec732b8 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.appRecovery +# @ohos.app.ability.appRecovery (Application Recovery) -The **appRecovery** module provides APIs for recovering faulty applications. +The **appRecovery** module provides APIs for recovering failed applications. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md index 3fb88a2b8ad93d3dbb5adf627f105d117ca86fda..f7203ef5de08d0151d65e2c65cf19b6e3855c1ea 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.errorManager +# @ohos.app.ability.errorManager (Error Manager) -The **ErrorManager** module provides APIs for registering and deregistering error observers. +The **errorManager** module provides APIs for registering and deregistering error observers. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-application-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md index 5326b582120b6dcbf23a88bedb1ff4dcbe6192ae..b1a98049c70502462a6225a63efd642c164ca60c 100644 --- a/en/application-dev/reference/apis/js-apis-application-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md @@ -1,6 +1,6 @@ -# @ohos.application.errorManager +# @ohos.application.errorManager (Error Manager) -The **ErrorManager** module provides APIs for registering and deregistering error observers. +The **errorManager** module provides APIs for registering and deregistering error observers. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 488c8f1633bc625610e122d37092cd2ed1ed254c..41d13ba5741ecf4324b1f4c859fb2a0a4bdf1d19 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,11 +1,10 @@ -# @ohos.batteryInfo +# @ohos.batteryInfo (Battery Information) The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status. > **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 ```js diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md index 7c1df26a13d242c8c875efea9c523b19752d1c34..2bb3159fc3912a6a1fe272451ce31aa812052432 100644 --- a/en/application-dev/reference/apis/js-apis-batteryStatistics.md +++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -1,4 +1,4 @@ -# @ohos.batteryStatistics +# @ohos.batteryStatistics (Battery Statistics) The **batteryStatistics** module provides APIs for querying software and hardware power consumption statistics. diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index b5c914e7725c878305ff0235a33d8d98d6c6d6e4..72e65e53e63380ef4ea0aa9b33796e236bc7ee84 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -1,11 +1,12 @@ -# Buffer +# @ohos.buffer (Buffer) -> **NOTE** -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +A **Buffer** object represents a byte sequence of a fixed length. It is used to store binary data. -A **Buffer** object represents a fixed-length sequence of bytes. It is used to store binary data. +You can use the APIs provided by the Buffer module to process images and a large amount of binary data, and receive or upload files. -You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, and receive or upload files. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -21,55 +22,23 @@ Enumerates the supported encoding formats of strings. | Encoding Format | Description | | ------- | -------------------- | -| ascii | ASCII format. | -| utf8 | UTF-8 | -| utf-8 | UTF-8 format.| -| utf16le | UTF-16LE format.| -| ucs2 | UTF-16LE format.| -| ucs-2 | UTF-16LE format.| -| base64 | Base64 format.| -| base64url | Base64 format.| -| latin1 | ASCII format.| -| binary | Binary format.| -| hex | Hexadecimal format.| - -## Buffer - -### Attributes - -**System capability**: SystemCapability.Utils.Lang - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Length of the buffer, in bytes.| -| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| -| byteOffset | number | Yes| No| Offset of the buffer in the memory pool.| - -**Error codes** - -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). - -| ID| Error Message| -| -------- | -------- | -| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | - -**Example** - -```ts -import buffer from '@ohos.buffer'; - -let buf = buffer.from("1236"); -console.log(JSON.stringify(buf.length)); -let arrayBuffer = buf.buffer; -console.log(JSON.stringify(new Uint8Array(arrayBuffer))); -console.log(JSON.stringify(buf.byteOffset)); -``` - -### alloc +| 'ascii' | ASCII format, which is case insensitive.| +| 'utf8' | UTF-8 format, which is case insensitive.| +| 'utf-8' | UTF-8 format, which is case insensitive.| +| 'utf16le' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs2' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs-2' | UTF-16 little-endian format, which is case insensitive.| +| 'base64' | Base64 format, which is case insensitive.| +| 'base64url' | Base64 format, which is case insensitive.| +| 'latin1' | ASCII format, which is case insensitive.| +| 'binary' | Binary format, which is case insensitive.| +| 'hex' | Hexadecimal format, which is case insensitive.| + +## buffer.alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer -Allocates and initializes a **Buffer** instance of the specified size. +Creates and initializes a **Buffer** instance of the specified length. **System capability**: SystemCapability.Utils.Lang @@ -77,8 +46,8 @@ Allocates and initializes a **Buffer** instance of the specified size. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| -| fill | string \| Buffer \| number | No| Pre-filled value. The default value is **0**.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| +| fill | string \| Buffer \| number | No| Value to be filled in the buffer. The default value is **0**.| | encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.| **Return value** @@ -97,12 +66,12 @@ let buf2 = buffer.alloc(5, 'a'); let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); ``` -### allocUninitializedFromPool +## buffer.allocUninitializedFromPool allocUninitializedFromPool(size: number): Buffer -Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it. -To initialize the **Buffer** instance, call **fill()**. +Creates a **Buffer** instance of the specified size from the buffer pool, without initializing it. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -110,7 +79,7 @@ To initialize the **Buffer** instance, call **fill()**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -127,11 +96,12 @@ let buf = buffer.allocUninitializedFromPool(10); buf.fill(0); ``` -### allocUninitialized +## buffer.allocUninitialized allocUninitialized(size: number): Buffer -Allocates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +Creates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -139,7 +109,7 @@ Allocates a **Buffer** instance of the specified size, without initializing it. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes|Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes|Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -156,7 +126,7 @@ let buf = buffer.allocUninitialized(10); buf.fill(0); ``` -### byteLength +## buffer.byteLength byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number @@ -169,7 +139,7 @@ Obtains the number of bytes of a string based on the encoding format. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format of the string. The default value is **utf-8**.| **Return value** @@ -187,7 +157,7 @@ console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8') // Print: ½ + ¼ = ¾: 9 characters, 12 bytes ``` -### compare +## buffer.compare compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1 @@ -221,11 +191,11 @@ let res = buf1.compare(buf2); console.log(Number(res).toString()); // Print 1. ``` -### concat +## buffer.concat concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer -Concatenates an array of **Buffer** instances into a new instance of the specified length. +Concatenates an array of **Buffer** instances of the specified length into a new instance. **System capability**: SystemCapability.Utils.Lang @@ -234,7 +204,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.| -| totalLength | number | No| Total length of the new **Buffer** instance, in bytes.| +| totalLength | number | No| Total length of bytes to be copied.| **Return value** @@ -244,7 +214,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -261,7 +231,7 @@ let buf = buffer.concat([buf1, buf2]); console.log(buf.toString('hex')); // 3132333461626364 ``` -### from +## buffer.from from(array: number[]): Buffer; @@ -290,11 +260,11 @@ let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); console.log(buf.toString('hex')); // 627566666572 ``` -### from +## buffer.from from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer -Creates a **Buffer** instance that shares memory with the specified array of **Buffer** instances. +Creates a **Buffer** instance of the specified length that shares memory with **arrayBuffer**. **System capability**: SystemCapability.Utils.Lang @@ -314,7 +284,7 @@ Creates a **Buffer** instance that shares memory with the specified array of **B **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -329,7 +299,7 @@ let ab = new ArrayBuffer(10); let buf = buffer.from(ab, 0, 2); ``` -### from +## buffer.from from(buffer: Buffer | Uint8Array): Buffer @@ -341,7 +311,7 @@ Creates a **Buffer** instance with the copy of another instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy. | +| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy.| **Return value** @@ -358,7 +328,7 @@ let buf1 = buffer.from('buffer'); let buf2 = buffer.from(buf1); ``` -### from +## buffer.from from(object: Object, offsetOrEncoding: number | string, length: number): Buffer @@ -385,10 +355,10 @@ Creates a **Buffer** instance based on the specified object. ```ts import buffer from '@ohos.buffer'; -let buf = buffer.from(new String('this is a test')); +let buf = buffer.from(new String('this is a test'), 'utf8', 14); ``` -### from +## buffer.from from(string: String, encoding?: BufferEncoding): Buffer @@ -418,11 +388,11 @@ let buf1 = buffer.from('this is a test'); let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); console.log (buf1.toString()); // Print: this is a test -console.log(buf2.toString()); +console.log (buf2.toString()); // print: this is a test ``` -### isBuffer +## buffer.isBuffer isBuffer(obj: Object): boolean @@ -454,7 +424,7 @@ buffer.isBuffer([]); // false buffer.isBuffer(new Uint8Array(1024)); // false ``` -### isEncoding +## buffer.isEncoding isEncoding(encoding: string): boolean @@ -485,6 +455,70 @@ console.log(buffer.isEncoding('utf/8').toString()); // Print: false console.log(buffer.isEncoding('').toString()); // Print: false ``` +## buffer.transcode + +transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer + +Transcodes the given **Buffer** or **Uint8Array** object from one encoding format to another. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | Buffer \| Uint8Array | Yes| Instance to encode.| +| fromEnc | string | Yes| Current encoding format.| +| toEnc | string | Yes| Target encoding format.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | New **Buffer** instance in the target encoding format.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(50); +let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); +console.log(newBuf.toString('ascii')); +``` + +## Buffer + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Length of the **Buffer** instance, in bytes.| +| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| +| byteOffset | number | Yes| No| Offset of the **Buffer** instance in the memory pool.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from("1236"); +console.log(JSON.stringify(buf.length)); +let arrayBuffer = buf.buffer; +console.log(JSON.stringify(new Uint8Array(arrayBuffer))); +console.log(JSON.stringify(buf.byteOffset)); +``` + ### compare compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 @@ -507,7 +541,15 @@ Compares this **Buffer** instance with another instance. | Type| Description| | -------- | -------- | -| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted. | +| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[targetStart/targetEnd/sourceStart/sourceEnd]" is out of range. | **Example** @@ -547,7 +589,7 @@ Copies data at the specified position in this **Buffer** instance to the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -578,6 +620,13 @@ Creates and returns an iterator that contains key-value pairs of this **Buffer** **System capability**: SystemCapability.Utils.Lang +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Key of the iterator.| +| number | Value of the iterator.| + **Example** ```ts @@ -647,7 +696,7 @@ Fills this **Buffer** instance at the specified position. By default, data is fi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -739,7 +788,7 @@ Creates and returns an iterator that contains the keys of this **Buffer** instan | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator.| +| IterableIterator<number> | Iterator created.| **Example** @@ -789,7 +838,7 @@ console.log(buf.lastIndexOf('buffer').toString()); // Print: 17 readBigInt64BE(offset?: number): bigint -Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset. +Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -807,7 +856,7 @@ Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at t **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -848,7 +897,7 @@ Reads a signed, little-endian 64-bit Big integer from this **Buffer** instance a **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -889,7 +938,7 @@ Reads an unsigned, big-endian 64-bit Big integer from this **Buffer** instance a **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -930,7 +979,7 @@ Reads an unsigned, little-endian 64-bit Big integer from this **Buffer** instanc **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -971,7 +1020,7 @@ Reads a big-endian double-precision floating-point number from this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1011,7 +1060,7 @@ Reads a little-endian double-precision floating-point number from this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1051,7 +1100,7 @@ Reads a big-endian single-precision floating-point number from this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1091,7 +1140,7 @@ Reads a little-endian single-precision floating-point number from this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1131,7 +1180,7 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1172,7 +1221,7 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1212,7 +1261,7 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1252,7 +1301,7 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1292,7 +1341,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1334,7 +1383,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1378,7 +1427,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1419,7 +1468,7 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1461,7 +1510,7 @@ Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1503,7 +1552,7 @@ Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1545,7 +1594,7 @@ Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1586,7 +1635,7 @@ Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1628,7 +1677,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1670,7 +1719,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1741,7 +1790,7 @@ Interprets this **Buffer** instance as an array of unsigned 16-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1776,7 +1825,7 @@ Interprets this **Buffer** instance as an array of unsigned 32-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1811,7 +1860,7 @@ Interprets this **Buffer** instance as an array of unsigned 64-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1901,7 +1950,7 @@ Creates and returns an iterator that contains the values of this **Buffer** inst | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator created.| +| IterableIterator<number> | Iterator.| **Example** @@ -1940,7 +1989,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1984,7 +2033,7 @@ Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2023,7 +2072,7 @@ Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2062,7 +2111,7 @@ Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2101,7 +2150,7 @@ Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2140,7 +2189,7 @@ Writes a big-endian double-precision floating-point number to this **Buffer** in **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2179,7 +2228,7 @@ Writes a little-endian double-precision floating-point number to this **Buffer** **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2218,7 +2267,7 @@ Writes a big-endian single-precision floating-point number to this **Buffer** in **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2258,7 +2307,7 @@ Writes a little-endian single-precision floating-point number to this **Buffer** **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2297,7 +2346,7 @@ Writes a signed 8-bit integer to this **Buffer** instance at the specified offse **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2338,7 +2387,7 @@ Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the sp **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2378,7 +2427,7 @@ Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2417,7 +2466,7 @@ Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the sp **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2457,7 +2506,7 @@ Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2497,7 +2546,7 @@ Writes a big-endian signed value of the specified length to this **Buffer** inst **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2538,7 +2587,7 @@ Writes a little-endian signed value of the specified length to this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2577,7 +2626,7 @@ Writes an unsigned 8-bit integer to this **Buffer** instance at the specified of **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2619,7 +2668,7 @@ Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2659,7 +2708,7 @@ Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2699,7 +2748,7 @@ Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2738,7 +2787,7 @@ Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2778,7 +2827,7 @@ Writes an unsigned big-endian value of the specified length to this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2818,7 +2867,7 @@ Writes an unsigned little-endian value of the specified length to this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2833,38 +2882,6 @@ let buf = buffer.allocUninitializedFromPool(6); buf.writeUIntLE(0x1234567890ab, 0, 6); ``` -### transcode - -transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer - -Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| source | Buffer \| Uint8Array | Yes| Instance to transcode. | -| fromEnc | string | Yes| Current encoding format.| -| toEnc | string | Yes| Target encoding format.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Buffer | New **Buffer** instance in the target encoding format.| - -**Example** - -```ts -import buffer from '@ohos.buffer'; - -let buf = buffer.alloc(50); -let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); -console.log(newBuf.toString('ascii')); -``` - ## Blob ### Attributes @@ -2941,7 +2958,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc **Return value** | Type| Description| | -------- | -------- | -| Blob | **Blob** instance created. | +| Blob | New **Blob** instance created.| **Example** ```ts @@ -2954,7 +2971,7 @@ let blob3 = blob.slice(0, 2, "MIME"); text(): Promise<string> -Returns text in UTF-8 format. +Returns text in UTF-8 format. This API uses a promise to return the result. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 544a4ba0d27e6c39794e063fc63282ba5455bf5e..89e14f7ad3e4fb3f525ccd9d5aab83b56e8c6521 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -1,4 +1,4 @@ -# Performance Tracing +# @ohos.bytrace (Performance Tracing) > **NOTE** > - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 7c5bd52bd9ccbc5ee7ad99b8a1e7311ce8c5f8d5..0ccd49a5dc2a8b8e3577b7614f8219573de7cf7d 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -1,6 +1,6 @@ -# Call +# @ohos.telephony.call (Call) -The call module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. +The **call** module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-observer.md#observeroncallstatechange). diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md new file mode 100644 index 0000000000000000000000000000000000000000..dc506245c6feef1b2c22b70613ce3359404162dc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cert.md @@ -0,0 +1,2109 @@ +# @ohos.security.cert (Certificate) + +The **certificate** module provides APIs for performing certificate operations. For details about the APIs for implementing the basic algorithm capabilities based on the cryptographic (crypto) framework, see [Crypto Framework](js-apis-cryptoFramework.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. + +## Modules to Import + +```javascript +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" +``` + +## CertResult + + Enumerates the error codes. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value | Description | +| --------------------------------------| -------- | -----------------------------| +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | This operation is not supported. | +| ERR_OUT_OF_MEMORY | 19020001 | Memory error. | +| ERR_RUNTIME_ERROR | 19020002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 19030001 | Crypto operation error. | +| ERR_CERT_SIGNATURE_FAILURE | 19030002 | The certificate signature verification failed. | +| ERR_CERT_NOT_YET_VALID | 19030003 | The certificate has not taken effect. | +| ERR_CERT_HAS_EXPIRED | 19030004 | The certificate has expired. | +| ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY | 19030005 | Failed to obtain the certificate issuer. | +| ERR_KEYUSAGE_NO_CERTSIGN | 19030006 | The key cannot be used for signing a certificate. | +| ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE | 19030007 | The key cannot be used for digital signature. | + +## DataBlob +Defines a binary data array. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data. | + +## DataArray + +Defines a list of data arrays. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data list. | + +## EncodingFormat + + Enumerates the certificate encoding formats. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value| Description | +| ---------- | ------ | --------- | +| FORMAT_DER | 0 | Distinguished Encoding Rules (DER) format.| +| FORMAT_PEM | 1 | Privacy-Enhanced Mail (PEM) format.| + + +## EncodingBlob + +Defines a certificate binary array in encoding format. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data.| +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## CertChainData + +Defines the certificate chain data, which is passed in as input parameters during certificate chain verification. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data, in the *length* (2 bytes) + *data* format. For example, **08ABCDEFGH07ABCDEFG**. The first two bytes indicate the length of the first certificate is eight bytes, and the following eight bytes indicate the certificate data. Then, the next two bytes indicate the length of another certificate is seven bytes, and the seven bytes followed indicate the certificate data.| +| count | number | Yes | Yes | Number of certificates contained in the input data. | +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Cert** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cer** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + } +}); +``` + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob) : Promise\ + +Creates an **X509Cert** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data.| + +**Return value** + +| Type | Description | +| ------- | ---------------- | +| Promise\ | **X509Cer** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Cert + +Provides APIs for X.509 certificate operations. + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the certificate signature. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the certificate signature. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 certificate data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized X.509 certificate data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + x509Cert.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 certificate data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | ---------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized X.509 certificate data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + x509Cert.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getPublicKey + +getPublicKey() : cryptoFramework.PubKey + +Obtains the public key of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| cryptoFramework.PubKey | X.509 certificate public key obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let pubKey = null; + try { + pubKey = x509Cert.getPublicKey(); + } catch (error) { + console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### checkValidityWithDate + +checkValidityWithDate(date: string) : void + +Checks the validity period of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------- | +| date | string | Yes | Date of the certificate to check. | + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let date = "150527000001Z"; + + // Verify the certificate validity period. + try { + x509Cert.checkValidityWithDate(date); + } catch (error) { + console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getVersion + +getVersion() : number + +Obtains the X.509 certificate version. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| number | X.509 certificate version obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let version = x509Cert.getVersion(); + } +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the X.509 certificate serial number. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | X.509 certificate serial number obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let serialNumber = x509Cert.getSerialNumber(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the X.509 certificate issuer. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- | +| [DataBlob](#datablob) | X.509 certificate issuer obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerName = x509Cert.getIssuerName(); + } +}); +``` + +### getSubjectName + +getSubjectName() : DataBlob + +Obtains the subject of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Subject name obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectName = x509Cert.getSubjectName(); + } +}); +``` + +### getNotBeforeTime + +getNotBeforeTime() : string + +Obtains the start time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Start time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notBefore = x509Cert.getNotBeforeTime(); + } +}); +``` + +### getNotAfterTime + +getNotAfterTime() : string + +Obtains the expiration time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Expiration time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notAfter = x509Cert.getNotAfterTime(); + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Signature data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let signature = x509Cert.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | X.509 certificate signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgName = x509Cert.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the object identifier (OID) of the X.509 certificate signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------- | +| string | OID obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgOid = x509Cert.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the signing algorithm parameters of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------ | +| [DataBlob](#datablob) | X.509 certificate signing algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgParams = x509Cert.getSignatureAlgParams(); + } +}); +``` + +### getKeyUsage + +getKeyUsage() : DataBlob + +Obtains the key usage of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Key usage of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let keyUsage = x509Cert.getKeyUsage(); + } +}); +``` + +### getExtKeyUsage + +getExtKeyUsage() : DataArray + +Obtains the usage of the extended key of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | Usage of the extended key obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let extKeyUsage = x509Cert.getExtKeyUsage(); + } +}); +``` + +### getBasicConstraints + +getBasicConstraints() : number + +Obtains the basic constraints for obtaining this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| number | Basic constraints obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let basicConstraints = x509Cert.getBasicConstraints(); + } +}); +``` + +### getSubjectAltNames + +getSubjectAltNames() : DataArray + +Obtains the Subject Alternative Names (SANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | SANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectAltNames = x509Cert.getSubjectAltNames(); + } +}); +``` + +### getIssuerAltNames + +getIssuerAltNames() : DataArray + +Obtains the Issuer Alternative Names (IANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | -------------------------- | +| [DataArray](#dataarray) | IANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerAltNames = x509Cert.getIssuerAltNames(); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Crl** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob) : Promise\ + +Creates an **X509Crl** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized CRL data.| + +**Return value** + +| Type | Description | +| ----------------- | -------------------- | +| Promise\ | Promise used to return the **X509Crl** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Crl + +Provides APIs for X.509 certificate CRL operations. + +### isRevoked + +isRevoked(cert : X509Cert) : boolean + +Checks whether an X.509 certificate is revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| cert | X509Cert | Yes | X.509 certificate to check.| + +**Return value** + +| Type | Description | +| --------- | --------------------------------------------- | +| boolean | Promise used to return the result. The value **true** indicates the certificate is revoked; the value **false** indicates the opposite.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let revokedFlag = x509Crl.isRevoked(x509Cert); + } catch (error) { + console.log("isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getType + +getType() : string + +Obtains the CRL type. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| string | CRL type obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let type = x509Crl.getType(); + } +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------ | +| callback | AsyncCallback\ | Yes | Callback invoked to return the serialized X.509 CRL data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 CRL data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ---------------------- | -------------------------------- | +| Promise\ | Promise used to return the serialized X.509 CRL data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the signature of the X.509 CRL. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type| Description | +| ---- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getVersion + +getVersion() : number + +Obtains the version of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| number | Version of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let version = x509Crl.getVersion(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the issuer of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Issuer of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let issuerName = x509Crl.getIssuerName(); + } +}); +``` + +### getLastUpdate + +getLastUpdate() : string + +Obtains the date when the X.509 CRL was last updated. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Last update date of the X.509 CRL.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let lastUpdate = x509Crl.getLastUpdate(); + } +}); +``` + +### getNextUpdate + +getNextUpdate() : string + +Obtains the date when the CRL will be updated the next time. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Next update date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let nextUpdate = x509Crl.getNextUpdate(); + } +}); +``` + +### getRevokedCert + +getRevokedCert(serialNumber : number) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified serial number of the certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | -------------- | +| serialNumber | number | Yes | Serial number of the certificate.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Set the serial number of the corresponding certificate. + let serialNumber = 1000; + try { + let entry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCertWithCert + +getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.| + +**Return value** + +| Type | Description | +| ------------ | -------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let entry = x509Crl.getRevokedCertWithCert(x509Cert); + } catch (error) { + console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCerts + +getRevokedCerts(callback : AsyncCallback>) : void + +Obtains all the revoked X.509 certificates. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts(function (error, array) { + if (error != null) { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getRevokedCerts success"); + } + }); + } +}); +``` + +### getRevokedCerts + +getRevokedCerts() : Promise> + +Obtains all the revoked X.509 certificates. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------------- | ---------------------- | +| Promise> | Promise used to return a list of revoked X.509 certificates.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts().then(array => { + console.log("getRevokedCerts success"); + }, error => { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getTbsInfo + +getTbsInfo() : DataBlob + +Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| [DataBlob](#datablob) | Promise used to return the **tbsCertList** information obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + try { + let tbsInfo = x509Crl.getTbsInfo(); + } catch (error) { + console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Signature data of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let signature = x509Crl.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| string | Signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgName = x509Crl.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------------------- | +| string | OID of the X.509 CRL signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgOid = x509Crl.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the parameters of the X.509 CRL signing algorithm. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------- | +| [DataBlob](#datablob) | Algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgParams = x509Crl.getSignatureAlgParams(); + } +}); +``` + +## cryptoCert.createCertChainValidator + +createCertChainValidator(algorithm :string) : CertChainValidator + +Creates a **CertChainValidator** object. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------ | +| algorithm | string | Yes | Certificate chain validator algorithm. Currently, only **PKIX** is supported.| + +**Return value** + +| Type | Description | +| ------------------ | -------------------- | +| CertChainValidator | **CertChainValidator** object created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +``` + +## CertChainValidator + +Provides APIs for certificate chain validator operations. + + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------- | +| algorithm | string | Yes | No | Algorithm used by the X509 certificate chain validator.| + + +### validate + +validate(certChain : CertChainData, callback : AsyncCallback\) : void + +Validates the X.509 certificate chain. This API uses an asynchronous callback to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the X.509 certificate chain is valid. If **error** is not **null**, the X.509 certificate chain is not valid.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData, function (error, data) { + if (error != null) { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("validate success"); + } +}); +``` + +### validate + +validate(certChain : CertChainData) : Promise\ + +Validates the X.509 certificate chain. This API uses a promise to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | -------------------------- | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData).then(result => { + console.log("validate success"); +}, error => { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### algorithm + +algorithm : string + +Obtains the algorithm of the X.509 certificate chain validator. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | Algorithm of the X.509 certificate chain validator obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +let algorithm = validator.algorithm; +``` + +## X509CrlEntry + +Provides APIs for operating the revoked certificates. + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized data of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized data of the revoked certificate obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized data of this revoked certificate. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized data of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded().then(result => { + console.log("getEncoded success"); +}, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the serial number of this revoked certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------------- | +| number | Serial number of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +let serialNumber = x509CrlEntry.getSerialNumber(); +``` + +### getCertIssuer + +getCertIssuer() : DataBlob + +Obtains the issuer of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- - | +| [DataBlob](#datablob) | Promise used to return the issuer of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let issuer = x509CrlEntry.getCertIssuer(); +} catch (error) { + console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` + +### getRevocationDate + +getRevocationDate() : string + +Obtains the date when the certificate was revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Promise used to return the certificate revocation date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let date = x509CrlEntry.getRevocationDate(); +} catch (error) { + console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index a166781108683f6b6fb53673da4deacd99882b26..2778a143c65125eca650324e67a220ab60f64ead 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -1,4 +1,4 @@ -# Contacts +# @ohos.contact (Contacts) >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md index 30d79a672420f70d0ab3067857e8726ab8a7ba32..4b6210a18736d99c786a2a305dc5ed534445b488 100644 --- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -1,9 +1,9 @@ -# Crypto Framework +# @ohos.security.cryptoFramework (Crypto Framework) -The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for crytographic operations. +The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. ## Modules to Import @@ -18,20 +18,23 @@ import cryptoFramework from "@ohos.security.cryptoFramework" **System capability**: SystemCapability.Security.CryptoFramework -| Name | Default Value | Description | -| --------------------------------------| -------- | -------------------------| -| INVALID_PARAMS | 401 | Invalid parameters. | -| NOT_SUPPORT | 801 | This operation is not supported. | -| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | -| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | -| ERR_CRYPTO_OPERATION | 17630001 | Crypto operation error. | +| Name | Value | Description | +| ------------------------------------- | -------- | ---------------------------- | +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | Unsupported operation. | +| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | +| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. | ## DataBlob + Defines a binary data array. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------| -| data | Uint8Array | Yes | Yes | Data. | + +| Name| Type | Readable| Writable| Description | +| ---- | ---------- | ---- | ---- | ------ | +| data | Uint8Array | Yes | Yes | Data.| + ## cryptoFramework.createMac @@ -53,6 +56,12 @@ Creates a **Mac** instance for message authentication code (MAC) operations. | ---- | --------------------------------------- | | Mac | [Mac](#mac) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -60,6 +69,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var mac; try { + // Set algName based on the algorithm supported. mac = cryptoFramework.createMac("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -70,7 +80,7 @@ try { Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework @@ -88,10 +98,16 @@ Initializes the MAC computation using a symmetric key. This API uses an asynchro **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| key | SymKey | Yes | Shared symmetric key. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------ | +| key | SymKey | Yes | Shared symmetric key.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -118,8 +134,6 @@ symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { }); ``` - - ### init init(key : SymKey) : Promise\; @@ -136,10 +150,16 @@ Initializes the MAC computation using a symmetric key. This API uses a promise t **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -149,9 +169,7 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); - } console.error("Mac algName is: " + mac.algName); @@ -175,10 +193,18 @@ Updates the MAC computation data. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -190,7 +216,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -220,16 +245,26 @@ Updates the MAC computation data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + +**Example** + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -237,14 +272,11 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { @@ -260,8 +292,6 @@ promiseConvertKey.then(symKey => { ``` - - ### doFinal doFinal(callback : AsyncCallback\) : void; @@ -270,10 +300,19 @@ Finalizes the MAC computation. This API uses an asynchronous callback to return **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------- | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -284,7 +323,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -323,10 +361,17 @@ Finalizes the MAC computation. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -339,7 +384,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -375,6 +419,12 @@ Obtains the MAC length, in bytes. | ------ | ------------------------- | | number | MAC length obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -387,7 +437,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -405,7 +454,7 @@ promiseConvertKey.then(symKey => { }).then(macOutput => { console.error("[Promise]: HMAC result: " + macOutput.data); let macLen = mac.getMacLength(); - AlertDialog.show({message: "MAC len: " + macLen}); + console.error("MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -431,6 +480,12 @@ Creates an **Md** instance for message digest operations. | ---- | ------------------------------------- | | Md | [Md](#md) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -438,6 +493,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var md; try { + // Set algName based on the algorithm supported. md = cryptoFramework.createMd("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -448,27 +504,34 @@ try { Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm to use.| +| algName | string | Yes | No | Digest algorithm.| ### update update(input : DataBlob, callback : AsyncCallback\) : void; -Updates the message digest data with the message passed in. This API uses an asynchronous callback to return the result. +Updates the message digest data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------ | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -495,20 +558,26 @@ md.update(blob, (err,) => { update(input : DataBlob) : Promise\; -Updates the message digest data with the message passed in. This API uses a promise to return the result. +Updates the message digest data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -539,10 +608,17 @@ Generates a message digest. This API uses an asynchronous callback to return the **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -581,10 +657,17 @@ Generates a message digest. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -622,7 +705,13 @@ Obtains the message digest length, in bytes. | Type | Description | | ------ | ------------------------ | -| number | Message digest length obtained. | +| number | Message digest length obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -645,7 +734,7 @@ promiseMdUpdate.then(() => { }).then(mdOutput => { console.error("[Promise]: MD result: " + mdOutput.data); let mdLen = md.getMdLength(); - AlertDialog.show({message: "MD len: " + mdLen}); + console.error("MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -665,6 +754,12 @@ Creates a **Random** instance for generating random numbers and setting seeds. | ------ | --------------------------------------------- | | Random | [Random](#random) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -679,7 +774,7 @@ try { ## Random -Provides APIs for computing random numbers. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). +Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). ### generateRandom @@ -689,10 +784,19 @@ Generates a random number of the given length. This API uses an asynchronous cal **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | **Example** @@ -722,16 +826,25 @@ Generates a random number of the given length. This API uses a promise to return **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | len | number | Yes | Length of the random number to generate.| **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -754,16 +867,21 @@ promiseGenerateRand.then(randData => { ### setSeed -setSeed(seed : DataBlob, callback : AsyncCallback\) : void; +setSeed(seed : DataBlob) : void; Sets a seed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------ | -| seed | DataBlob | Yes | Seed to set. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| seed | DataBlob | Yes | Seed to set.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------- | +| 17620001 | memory error | **Example** @@ -782,94 +900,70 @@ rand.generateRandom(12, (err, randData) => { console.error("[Callback] err: " + err.code); } else { console.error("[Callback]: generate random result: " + randData.data); - rand.setSeed(randData, (err1, data) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: setSeed success"); - } - }); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } } }); ``` -### setSeed - -setSeed(seed : DataBlob) : Promise\; - -Sets a seed. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.CryptoFramework - -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| seed | DataBlob | Yes | Seed to set.| - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} - -var promiseGenerateRand = rand.generateRandom(12); -promiseGenerateRand.then(randData => { - console.error("[Promise]: rand result: " + randData.data); - var promiseSetSeed = rand.setSeed(randData); - return promiseSetSeed; -}).then(() => { - console.error("[Promise]: setSeed success"); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` - ## ParamsSpec -Defines the parameters for encryption and decryption. For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). You do not need to construct the child class object if the IV is not required. +Defines the parameters used for encryption and decryption.
For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2). **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters.
Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode. | +| Name | Type | Readable| Writable| Description | +| -------- | ------ | ---- | ---- | ----------------------- | +| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC,|CTR,|OFB, |and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| + +> **NOTE** +> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), while a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you must set **algoName** for the parent class **ParamsSpec** to let the algorithm library know the child class object to pass in in **init()**. ## IvParamsSpec -Defines the parameters for the CBC, CTR, OFB, and CFB modes, which require only an IV for each encryption operation. For the symmetric encryption and decryption that use the CBC, CTR, OFB, or CFB mode, you need to construct **IvParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption.
Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB or CFB mode: 8-byte IV | +| Name| Type | Readable| Writable| Description | +| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, |CTR, |OFB, |or CFB mode: 16-byte IV
- 3DES CBC,|OFB, or |CFB mode: 8-byte IV| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## GcmParamsSpec -Defines the parameters for the GCM mode. For the symmetric encryption and decryption that use the GCM mode, you need to construct **GcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**GcmParamsSpec** applies to the GCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes.| -| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes.| -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 16 bytes.
When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) for decryption.| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CcmParamsSpec -Defines the parameters for the CCM mode. For the symmetric encryption and decryption that use the CCM mode, you need to construct **CcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**CcmParamsSpec** applies to the CCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | -------- | ---- | ---- | -------------------------------| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | | iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | | aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 12 bytes.
When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) for decryption.| +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CryptoMode @@ -877,22 +971,22 @@ Enumerates the cryptographic operations. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Value | Description | -| ------------ | -------- | -------------------------------- | -| ENCRYPT_MODE | 0 | Encryption. | -| DECRYPT_MODE | 1 | Decryption. | +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| ENCRYPT_MODE | 0 | Encryption.| +| DECRYPT_MODE | 1 | Decryption.| ## Key -Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. Keys can be generated by a key generator. +Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -905,48 +999,50 @@ Obtains the key in hexadecimal format. This API returns the result synchronously **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## SymKey -Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). +Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); -console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. +console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. key.clearMem(); encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s. @@ -954,15 +1050,15 @@ console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display a ## PubKey -Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Public keys can be generated by an **AsyKeyGenerator**. +Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Public keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| @@ -976,30 +1072,37 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## PriKey -Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Private keys can be generated by an **AsyKeyGenerator**. +Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Private keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -1012,52 +1115,74 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. key.clearMem(); ``` +## KeyPair + +Defines an asymmetric key pair, which includes a public key and a private key.
Asymmetric key pairs can be generated by the **AsyKeyGenerator**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------ | +| priKey | [PriKey](#prikey) | Yes | No | Private key. | +| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | + + ## cryptoFramework.createSymKeyGenerator createSymKeyGenerator(algName : string) : SymKeyGenerator -Creates a **SymKeyGenerator** instance based on the specified algorithm. For details about the supported symmetric key parameters, see "String for Generating a Key" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Creates a **symKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ----------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String for Generating a Key" in [Key Generation Specifications] (../../security/cryptoFramework-overview.md#key-generation-specifications).| **Return value** -| Type | Description | +| Type | Description | | ----------------------------------- | -------------------------- | -| [SymKeyGenerator](#symkeygenerator) | **SymKeyGenerator** instance created.| +| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| **Example** @@ -1068,29 +1193,35 @@ let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); ## SymKeyGenerator -Provides APIs for using the **symKeyGenerator**. Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +Provides APIs for using the **symKeyGenerator**.
Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------ | | algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| ### generateSymKey generateSymKey(callback : AsyncCallback\) : void -Generates a key randomly. This API uses an asynchronous callback to return the result. +Generates a key randomly. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ------------------- | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | **Example** @@ -1099,11 +1230,11 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); symKeyGenerator.generateSymKey((err, symKey) => { - if (err) { - console.error('Failed to generate symKey'); - return; - } - console.log('Generate symKey success, algName: ' + symKey.algName); + if (err) { + console.error(`Generate symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Generate symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1111,24 +1242,33 @@ symKeyGenerator.generateSymKey((err, symKey) => { generateSymKey() : Promise\ -Generates a key randomly. This API uses a promise to return the result. +Generates a key randomly. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | + **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = 'AES128'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); -symKeyGenerator.generateSymKey().then((symKey) => { - console.log('Generate symKey success, algName:' + symKey.algName); +symKeyGenerator.generateSymKey() +.then(symKey => { + console.info(`Generate symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Generate symKey failed, ${error.code}, ${error.message}`); }) ``` @@ -1136,16 +1276,22 @@ symKeyGenerator.generateSymKey().then((symKey) => { convertKey(key : DataBlob, callback : AsyncCallback\) : void -Converts a key. This API uses an asynchronous callback to return the result. +Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ---------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert. | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| key | [DataBlob](#datablob) | Yes | Data to convert. | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------- | +| 17620001 | memory error. | **Example** @@ -1164,12 +1310,12 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { - if (err) { - console.error('Failed to convert symKey'); - return; - } - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { + if (err) { + console.error(`Convert symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Convert symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1177,22 +1323,28 @@ symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { convertKey(key : DataBlob) : Promise\ -Converts a key. This API uses a promise to return the result. +Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| key | [DataBlob](#datablob) | Yes | Data to convert.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------- | +| 17620001 | memory error. | + **Example** ```js @@ -1210,14 +1362,18 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial).then((symKey) => { - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob) +.then(symKey => { + console.info(`Convert symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Convert symKey failed, ${error.code}, ${error.message}`); }) ``` ## cryptoFramework.createAsyKeyGenerator createAsyKeyGenerator(algName : string) : AsyKeyGenerator + Creates an **AsyKeyGenerator** instance based on the specified algorithm. **System capability**: SystemCapability.Security.CryptoFramework @@ -1226,12 +1382,12 @@ Creates an **AsyKeyGenerator** instance based on the specified algorithm. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| **Return value** -| Type | Description | -| --------------- | -------------------------- | +| Type | Description | +| --------------- | ---------------------------- | | asyKeyGenerator | **AsyKeyGenerator** instance created.| **Example** @@ -1250,23 +1406,22 @@ Provides APIs for using the **AsKeyGenerator**. Before using any API of the **As **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------------------------| -| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**. | - - +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------------- | +| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| ### generateKeyPair generateKeyPair(callback : AsyncCallback\) : void; + Generates a key pair randomly. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** @@ -1288,14 +1443,15 @@ asyKeyGenerator.generateKeyPair((err, keyPair) => { ### generateKeyPair generateKeyPair() : Promise\ + Generates a key pair randomly. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1315,23 +1471,25 @@ keyGenPromise.then( keyPair => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void -Converts an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------ | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" - +let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here. +let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here. let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { if (err) { @@ -1345,21 +1503,22 @@ asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ -Converts an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------- | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1368,6 +1527,8 @@ Converts an asymmetric key. This API uses a promise to return the result. For de import cryptoFramework from "@ohos.security.cryptoFramework" let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here. +let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here. let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey); keyGenPromise.then( keyPair => { console.info("convertKey success."); @@ -1378,28 +1539,32 @@ keyGenPromise.then( keyPair => { **Key Conversion** -- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 and PKCS #8 formats is returned, respectively. The data can be used for cross-application transfer or persistent storage. +- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage. - The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -- In **convertKey()**, **pubKey** and **priKey** are optional. Either **pubKey** or **priKey** can be passed in. As a result, the returned **KeyPair** instance contains only the key converted from the data you passed in. +- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. ## cryptoFramework.createCipher createCipher(transformation : string) : Cipher -Creates a [Cipher](#cipher) instance based on the specified algorithm. -For details about the supported algorithms, see "Algorithm String" in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). + +Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | -------- | ------------------------------------------------------------ | -| transformation | string | Yes | Combination of the algorithm name, encryption mode, and padding algorithm of the **Cipher** instance to create. For example, **RSA1024\|PKCS1** or **RSA1024\|PKCS1_OAEP\|SHA256\|SHA256**.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details about, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). | + +> **NOTE** +> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. +> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. **Return value** -| Type | Description | -| ------ | ------------------------ | +| Type | Description | +| ----------------- | ------------------------ | | [Cipher](#cipher) | [Cipher](#cipher) instance created.| **Example** @@ -1414,39 +1579,51 @@ try { console.info(`cipher algName: ${cipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); - return; } ``` ## Cipher -Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. For details about the complete encryption and decryption process, see [Encryption and Decryption Operations](../../security/cryptoFramework-guidelines.md#encryption-and-decryption-operations). +Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). + +A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. + +- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation. +- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable | Writable | Description | -| ------- | ------ | -------- | ----------- | ---------------------------- | -| algName | string | Yes | No | Algorithm to use.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm.| ### init init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void -Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. +Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------ | ------- | ------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1454,13 +1631,14 @@ Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. + cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { if (err) { - console.error('Failed to init cipher'); - return; + console.error(`Failed to init cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. } - console.log('Init cipher success'); - // Perform subsequent operations such as update. }) ``` @@ -1468,23 +1646,31 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ -Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. +Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
**init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ---------- | ---- | ---------------------- | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption.| -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. | +| Name | Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| **Return value** -| Type | Description | -| ------------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1492,9 +1678,12 @@ Initializes a [cipher](#cipher) instance. This API uses a promise to return the import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { - console.log('Init cipher success'); +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) +.then(() => { + console.info(`Init cipher success`); // Perform subsequent operations such as update. +}, error => { + console.error(`Failed to init cipher, ${error.code}, ${error.message}`); }) ``` @@ -1502,16 +1691,29 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { update(data : DataBlob, callback : AsyncCallback\) : void -Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1531,11 +1733,14 @@ let cipher; // The process of creating a Cipher instance is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; cipher.update(plainText, (err, output) => { // Example of the encryption process. if (err) { - console.error('Failed to update cipher'); - return; + console.error(`Failed to update cipher`); + } else { + console.info(`Update cipher success`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). } - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. }) ``` @@ -1543,21 +1748,34 @@ cipher.update(plainText, (err, output) => { // Example of the encryption p update(data : DataBlob) : Promise\ -Updates the data to encrypt or decrypt by segment. This API uses a promise to return the result. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output. That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to returns the **DataBlob** (containing the encrypted or decrypted data).| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1575,9 +1793,15 @@ function stringToUint8Array(str) { let cipher; // The process of creating a Cipher instance is omitted here. // The init() process is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(data).then((output) => { - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. +cipher.update(plainText) +.then((output) => { + console.info(`Update cipher success.`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). +}, error => { + console.info(`Update cipher failed.`); }) ``` @@ -1585,23 +1809,33 @@ cipher.update(data).then((output) => { doFinal(data : DataBlob, callback : AsyncCallback\) : void -Finalizes the data encryption or decryption operation. This API uses an asynchronous callback to return the result. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. -- For symmetric encryption and decryption in other modes, the output can be either of the following: - (1) **Update()** returns part of the encryption and decryption result, and **doFinal()** returns the remaining encryption and decryption result. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. + +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.
If data is already passed in by [update()](#update-4), **data** can be **null**. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1613,10 +1847,13 @@ let data; // The process of preparing the data to encrypt or decrypt i // The init() and update() processes are omitted here. cipher.doFinal(data, (err, output) => { if (err) { - console.error('Failed to final cipher'); - return; + console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } } - console.log('Final cipher success'); }) ``` @@ -1624,31 +1861,38 @@ cipher.doFinal(data, (err, output) => { doFinal(data : DataBlob) : Promise\ -Finalizes the data encryption or decryption operation. This API uses a promise to return the result. - -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. - -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -- For symmetric encryption and decryption in other modes, the output includes the following: +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. **authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. - (1) **Update()** returns part of the encryption and decryption results, and **doFinal()** returns the remaining encryption and decryption results. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. If data is already passed in by [update()](#update-4), **data** can be **null**. | +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1658,22 +1902,37 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let cipher; // The process of creating a Cipher instance is omitted here. let data; // The process of preparing the data to encrypt or decrypt is omitted here. // The init() and update() processes are omitted here. -cipher.doFinal(data).then((output) => { - console.log('Final cipher success'); +cipher.doFinal(data) +.then(output => { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } +}, error => { + console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); }) ``` -**Callback example**: +**RSA encryption example (callback)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); rsaGenerator.generateKeyPair(function (err, keyPair) { let pubKey = keyPair.pubKey; cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { - let input = {data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = {data : stringToUint8Array(plainText) }; cipher.doFinal(input, function (err, data) { AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); }); @@ -1681,11 +1940,19 @@ rsaGenerator.generateKeyPair(function (err, keyPair) { }); ``` -**Promise example**: +**RSA encryption example (promise)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); let keyGenPromise = rsaGenerator.generateKeyPair(); @@ -1693,13 +1960,16 @@ keyGenPromise.then(rsaKeyPair => { let pubKey = rsaKeyPair.pubKey; return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. }).then(() => { - let input = { data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = { data : stringToUint8Array(plainText) }; return cipher.doFinal(input); }).then(dataBlob => { console.info("EncryptOutPut is " + dataBlob.data); }); ``` +> **NOTE** +> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data). ## cryptoFramework.createSign @@ -1717,9 +1987,9 @@ Creates a **Sign** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Sign | **Sign** instance created.| +| Type| Description | +| ---- | -------------------------------- | +| Sign | **Sign** instance created.| **Example** @@ -1728,46 +1998,58 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256") ``` ## Sign -Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. +Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. +The signing mode is determined in **createSign()**, and the key is set by **init()**. +If the data to be signed is short, you can call **sign()** to pass in the data for signing after **init()**. +If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. +If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to use.| ### init init(priKey : PriKey, callback : AsyncCallback\) : void -Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. +Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init -init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ +init(priKey : PriKey) : Promise\ -Initializes a **Sign** instance using a private key. This API uses a promise to return the result. +Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1780,10 +2062,10 @@ Updates the data to be signed. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1797,12 +2079,12 @@ Updates the data to be signed. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### sign @@ -1815,10 +2097,10 @@ Signs the data. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### sign @@ -1832,53 +2114,92 @@ Signs the data. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -rsaGenerator.generateKeyPair(function (err, keyPair) { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - signer.init(priKey, function (err, data) { - signer.update(input1, function (err, data) { - signer.sign(input2, function (err, data) { - SignMessageBlob = data; - console.info("sign output is " + SignMessageBlob.data); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessageCallback() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + rsaGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + signer.init(priKey, function (err, data) { + signer.update(input1, function (err, data) { // Add the first segment of the data. + signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. + SignMessageBlob = data; + AlertDialog.show({message : "res" + SignMessageBlob.data}); + }); }); }); }); -}); +} ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let keyGenPromise = rsaGenerator.generateKeyPair(); -keyGenPromise.then( keyPair => { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - return signer.init(priKey); -}).then(() => { - return signer.update(input1); -}).then(() => { - return signer.sign(input2); -}).then(dataBlob => { - SignMessageBlob = dataBlob; - console.info("sign output is " + SignMessageBlob.data); -}); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessagePromise() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let keyGenPromise = rsaGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + return signer.init(priKey); + }).then(() => { + return signer.update(input1); // Add the first segment of the data. + }).then(() => { + return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. + }).then(dataBlob => { + SignMessageBlob = dataBlob; + console.info("sign output is " + SignMessageBlob.data); + AlertDialog.show({message : "output" + SignMessageBlob.data}); + }); +} ``` ## cryptoFramework.createVerify @@ -1897,9 +2218,9 @@ Creates a **Verify** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Verify | **Verify** instance created.| +| Type | Description | +| ------ | ---------------------------------- | +| Verify | **Verify** instance created.| **Example** @@ -1908,11 +2229,27 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); -let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") ``` + ## Verify Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**. +The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. +The signature verification mode is determined in **createVerify()**, and key is set by **init()**. +If the data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**. +If the data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data. +If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to be used for signature verification.| + + ### init @@ -1924,12 +2261,13 @@ Initializes the **Verify** instance using a public key. This API uses an asynchr **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes| Public key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init + init(pubKey : PubKey) : Promise\ Initializes the **Verify** instance using a public key. This API uses a promise to return the result. @@ -1938,14 +2276,14 @@ Initializes the **Verify** instance using a public key. This API uses a promise **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes|Public key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1958,10 +2296,10 @@ Updates the data for signature verification. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1975,12 +2313,12 @@ Updates the data for signature verification. This API uses a promise to return t | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### verify @@ -1993,11 +2331,11 @@ Verifies the signature. This API uses an asynchronous callback to return the res **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| signatureData | DataBlob | Yes | Signature data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### verify @@ -2009,25 +2347,30 @@ Verifies the signature. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in.| -| signatureData | DataBlob| Yes| Signature data.| +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| ----------------- | ---------------------------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); verifyer.init(globalKeyPair.pubKey, function (err, data) { verifyer.update(input1, function(err, data) { - verifyer.verify(input2, SignMessageBlob, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { console.info("verify result is " + data); }) }); @@ -2035,19 +2378,25 @@ verifyer.init(globalKeyPair.pubKey, function (err, data) { ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. verifyInitPromise.then(() => { return verifyer.update(input1); }).then(() => { - return verifyer.verify(input2, SignMessageBlob); + return verifyer.verify(input2, signMessageBlob); }).then(res => { console.log("Verify result is " + res); }); ``` + ## cryptoFramework.createKeyAgreement createKeyAgreement(algName : string) : KeyAgreement @@ -2058,15 +2407,15 @@ Creates a **KeyAgreement** instance. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------- | +| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.| **Return value** -| Type| Description | -| ---- | ------------------------------ | -| KeyAgreement | **KeyAgreement** instance created.| +| Type | Description | +| ------------ | ---------------------------------------- | +| KeyAgreement | **KeyAgreement** instance created.| **Example** @@ -2079,7 +2428,15 @@ let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); ## KeyAgreement -Provides APIs for key agreement operations. Before using any API of the **keyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. +Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm used for key agreement.| ### generateSecret @@ -2091,13 +2448,14 @@ Generates a shared secret. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret generated. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret.| ### generateSecret + generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\ Generates a shared secret. This API uses a promise to return the result. @@ -2106,21 +2464,23 @@ Generates a shared secret. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| **Return value** -| Type | Description | -| --------------- | ------------ | -| Promise\ | Promise used to return the shared secret generated. | +| Type | Description | +| ------------------ | -------- | +| Promise\ | Promise used to return the shared secret.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { if (err) { @@ -2132,9 +2492,11 @@ keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); keyAgreementPromise.then((secret) => { diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index ccc1f7b4e26c0cbc6556f2ea767c5601ac3a477e..4cdef60fa628733e5be8cc6df783548b7b5bcd07 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,4 +1,4 @@ -# @ohos.data.dataShareResultSet +# @ohos.data.dataShareResultSet (DataShare Result Set) The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index 779d30c40263eecd1a8ecf70209a95008aa228dd..f41bea4da45a6f6c0224e126f698d45d274e25dc 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,4 +1,4 @@ -# DataAbilityPredicates +# @ohos.data.dataAbility (DataAbility Predicates) **DataAbility** provides APIs for creating predicates, which implement different query methods for relational database (RDB) stores. @@ -23,16 +23,16 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of a database table.| - | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a database table.| +| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | **Return value** - | Type| Description| - | -------- | -------- | - | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| +| Type| Description| +| -------- | -------- | +| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -56,16 +56,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -83,16 +83,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -110,9 +110,9 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** @@ -135,9 +135,9 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** @@ -160,9 +160,9 @@ Adds the OR condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** @@ -182,9 +182,9 @@ Adds the AND condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** @@ -204,16 +204,16 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -231,16 +231,16 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -258,16 +258,16 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -285,15 +285,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -311,15 +311,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -337,16 +337,16 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -364,16 +364,16 @@ Sets a **DataAbilityPredicates** object to match the specified string. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -391,17 +391,17 @@ Sets a **DataAbilityPredicates** object to match a field whose data type is **Va **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -419,17 +419,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -447,16 +447,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -474,16 +474,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -501,16 +501,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -528,16 +528,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -555,15 +555,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -581,15 +581,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -607,9 +607,9 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| **Example** @@ -627,15 +627,15 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Maximum number of records.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Maximum number of records.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| **Example** @@ -653,15 +653,15 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| **Example** @@ -680,15 +680,15 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fields | Array<string> | Yes| Names of columns to group.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fields | Array<string> | Yes| Names of columns to group.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| **Example** @@ -706,15 +706,15 @@ Sets a **DataAbilityPredicates** object to specify the index column. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | indexName | string | Yes| Name of the index column.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| indexName | string | Yes| Name of the index column.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| **Example** @@ -732,17 +732,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -760,16 +760,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index 2a476aaf33cc927b8c0ec5c392a083b6b42c8f80..82a333b14b2ea90e92540ee31142ea884c7f2593 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,4 +1,4 @@ -# @ohos.data.dataShare +# @ohos.data.dataShare (DataShare) The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 4d2df994d96b7b0986782774e9d531a12750cac7..78d896c54a2f1c1674825ddaff66088634129596 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,4 +1,4 @@ -# Data Share Predicates +# @ohos.data.dataSharePredicates (DataShare Predicates) You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. @@ -35,7 +35,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -65,7 +65,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -439,8 +439,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -470,8 +470,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -501,7 +501,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -531,7 +531,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -561,7 +561,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -591,7 +591,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -790,7 +790,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes| Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** @@ -820,7 +820,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 6f24aa3255f0340e0ad8ef248ae25d62092e0774..dc8bf8258b987e9e4ad2799516ee6aafeb487896 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,4 +1,4 @@ -# Distributed Data Object +# @ohos.data.distributedDataObject (Distributed Data Object) The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. @@ -23,9 +23,9 @@ Creates a distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | source | object | Yes| Attribute of the distributed data object to create.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | object | Yes| Attribute of the distributed data object to create.| **Return value** | Type| Description| @@ -49,9 +49,9 @@ Creates a random session ID. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Return value** - | Type| Description| - | -------- | -------- | - | string | Session ID created.| +| Type| Description| +| -------- | -------- | +| string | Session ID created.| **Example** ```js @@ -97,15 +97,15 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | **Example** @@ -128,10 +128,10 @@ Subscribes to the changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js @@ -157,10 +157,10 @@ Unsubscribes from the changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** @@ -182,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** ```js @@ -207,10 +207,10 @@ Unsubscribes from the status change (online or offline) of this distributed data **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| **Example** @@ -243,10 +243,10 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| - | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| +| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** ```js @@ -279,15 +279,15 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Type| Description| +| -------- | -------- | +| Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** @@ -317,9 +317,9 @@ If the object is stored on another device, the data on the local device will be **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** @@ -345,9 +345,9 @@ If the object is stored on another device, the data on the local device will be **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Type| Description| +| -------- | -------- | +| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index cad744cb266c3c5712de9d441fe0a56a1fc4ccbc..2b5f66fd6b58e4b29b4fd9201a5bbd9a03a41f34 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,4 +1,4 @@ -# Preferences +# @ohos.data.preferences (Preferences) The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. @@ -497,7 +497,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 89ebac58ef1f970c8c97c00bedb0fe5552491115..bcebd097f34c1337e5826e866302af9626696a32 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,4 +1,4 @@ -# @ohos.data.rdb +# @ohos.data.rdb (RDB) The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md index 1d3451af2d899c34d1b73f2669c688cac7d6f464..e6b33f3544ead35cb0584365c1c806f02b30ad1f 100644 --- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -62,8 +62,8 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { console.info("Failed to get RdbStore, err: " + err) return } - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) { - console.log("RdbStore status is ON_CREATA") + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { console.log("RdbStore status is ON_OPEN") } else { @@ -97,8 +97,8 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { console.info("Failed to get RdbStore, err: " + err) return } - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) { - console.log("RdbStore status is ON_CREATA") + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { console.log("RdbStore status is ON_OPEN") } else { @@ -154,8 +154,8 @@ const STORE_CONFIG = { } let promise = data_rdb.getRdbStore(context, STORE_CONFIG); promise.then(async (rdbStore) => { - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) { - console.log("RdbStore status is ON_CREATA") + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { console.log("RdbStore status is ON_OPEN") } else { @@ -188,8 +188,8 @@ const STORE_CONFIG = { } let promise = data_rdb.getRdbStore(context, STORE_CONFIG); promise.then(async (rdbStore) => { - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) { - console.log("RdbStore status is ON_CREATA") + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { console.log("RdbStore status is ON_OPEN") } else { diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md index 798ac7bba0926f47e1bc16eb6b672403bc082fa7..8cdecd1134a270075b3d4dd86a7e4e7a07fc7390 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,549 +1,17 @@ -# Result Set +# resultSet A result set is a set of results returned after the relational database (RDB) query APIs are called. You can use the **resultset** APIs to obtain required data. -> **NOTE** +> **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. +> +> The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore#ResultSet](js-apis-data-relationalStore.md#resultset). -## ResultSetV99+ - -Provides methods to access the result set, which is obtained by querying the RDB store. - -### Usage - -You need to obtain the **resultSetV9** instance by using [RdbStoreV9.query()](js-apis-data-rdb.md#query). - -```js -import dataRdb from '@ohos.data.rdb'; -let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -predicatesV9.equalTo("AGE", 18); -let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSetV9) => { - console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount); -}); -``` - -### Attributes9+ - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Type | Mandatory| Description | -| ------------ | ------------------- | ---- | -------------------------------- | -| columnNames | Array<string> | Yes | Names of all columns in the result set. | -| columnCount | number | Yes | Number of columns in the result set. | -| rowCount | number | Yes | Number of rows in the result set. | -| rowIndex | number | Yes | Index of the current row in the result set. | -| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | -| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | -| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| -| isStarted | boolean | Yes | Whether the cursor has been moved. | -| isClosed | boolean | Yes | Whether the result set is closed. | - -### getColumnIndex9+ - -getColumnIndex(columnName: string): number - -Obtains the column index based on the column name. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------------------------- | -| columnName | string | Yes | Column name specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| number | Index of the column obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -resultSetV9.goToFirstRow(); -const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID")); -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### getColumnName9+ - -getColumnName(columnIndex: number): string - -Obtains the column name based on the column index. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------- | -| columnIndex | number | Yes | Column index specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| string | Column name obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const id = resultSetV9.getColumnName(0); -const name = resultSetV9.getColumnName(1); -const age = resultSetV9.getColumnName(2); - ``` - -### goTo9+ - -goTo(offset:number): boolean - -Moves the cursor to the row based on the specified offset. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------- | -| offset | number | Yes | Offset relative to the current position.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoto.then((resultSetV9) => { - resultSetV9.goTo(1); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToRow9+ - -goToRow(position: number): boolean - -Moves the cursor to the specified row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------ | -| position | number | Yes | Position to which the cursor is to be moved.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygotorow.then((resultSetV9) => { - resultSetV9.goToRow(5); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToFirstRow9+ - -goToFirstRow(): boolean - - -Moves the cursor to the first row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoFirst.then((resultSetV9) => { - resultSetV9.goToFirstRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToLastRow9+ - -goToLastRow(): boolean - -Moves the cursor to the last row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoLast.then((resultSetV9) => { - resultSetV9.goToLastRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToNextRow9+ - -goToNextRow(): boolean - -Moves the cursor to the next row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoNext.then((resultSetV9) => { - resultSetV9.goToNextRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToPreviousRow9+ - -goToPreviousRow(): boolean - -Moves the cursor to the previous row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoPrev.then((resultSetV9) => { - resultSetV9.goToPreviousRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### getBlob9+ - -getBlob(columnIndex: number): Uint8Array - -Obtains the value in the specified column in the current row as a byte array. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ---------- | -------------------------------- | -| Uint8Array | Value in the specified column as a byte array.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES")); - ``` - -### getString9+ - -getString(columnIndex: number): string - -Obtains the value in the specified column in the current row as a string. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| string | Value in the specified column as a string.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); - ``` - -### getLong9+ - -getLong(columnIndex: number): number - -Obtains the value in the specified column in the current row as a Long. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | -------------------------- | -| number | Value in the specified column as a Long.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); - ``` - -### getDouble9+ - -getDouble(columnIndex: number): number - -Obtains the value in the specified column in the current row as a double. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| number | Value in the specified column as a double.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### isColumnNull9+ - -isColumnNull(columnIndex: number): boolean - -Checks whether the value in the specified column of the current row is null. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------------------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES")); - ``` - -### close9+ - -close(): void - -Closes this result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Example** - - ```js -let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSetV9) => { - resultSetV9.close(); -}).catch((err) => { - console.log('Failed to close the resultset'); -}); - ``` - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -## ResultSet(deprecated) +## ResultSet Provides methods to access the result set, which is obtained by querying the RDB store. -> **NOTE** -> -> This object is supported since API version 7 and deprecated since API version 9. You are advised to use [ResultSetV9](#resultsetv99). - ### Usage You need to obtain a **resultSet** object by using [RdbStore.query()](js-apis-data-rdb.md#query). @@ -559,11 +27,7 @@ promise.then((resultSet) => { }); ``` -### Attributes(deprecated) - -> **NOTE** -> -> This parameter is supported since API version 7 and is deprecated since API version 9. You are advised to use [Attributes](#attributes9). +### Attributes **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -579,29 +43,25 @@ promise.then((resultSet) => { | isStarted | boolean | Yes| Whether the cursor has been moved.| | isClosed | boolean | Yes| Whether the result set is closed.| -### getColumnIndex(deprecated) +### getColumnIndex getColumnIndex(columnName: string): number Obtains the column index based on the column name. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnIndex](#getcolumnindex9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnName | string | Yes| Column name specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnName | string | Yes| Column name specified.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Index of the column obtained.| + | Type| Description| + | -------- | -------- | + | number | Index of the column obtained.| **Example** @@ -613,29 +73,25 @@ Obtains the column index based on the column name. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### getColumnName(deprecated) +### getColumnName getColumnName(columnIndex: number): string Obtains the column name based on the column index. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnName](#getcolumnname9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Column index specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Column index specified.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Column name obtained.| + | Type| Description| + | -------- | -------- | + | string | Column name obtained.| **Example** @@ -645,29 +101,25 @@ Obtains the column name based on the column index. const age = resultSet.getColumnName(2); ``` -### goTo(deprecated) +### goTo goTo(offset:number): boolean Moves the cursor to the row based on the specified offset. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goTo](#goto9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| offset | number | Yes| Offset relative to the current position.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | offset | number | Yes| Offset relative to the current position.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -682,29 +134,25 @@ Moves the cursor to the row based on the specified offset. }); ``` -### goToRow(deprecated) +### goToRow goToRow(position: number): boolean Moves the cursor to the specified row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToRow](#gotorow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| position | number | Yes| Position to which the cursor is to be moved.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | position | number | Yes| Position to which the cursor is to be moved.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -719,23 +167,19 @@ Moves the cursor to the specified row in the result set. }); ``` -### goToFirstRow(deprecated) +### goToFirstRow goToFirstRow(): boolean Moves the cursor to the first row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToFirstRow](#gotofirstrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -750,23 +194,19 @@ Moves the cursor to the first row of the result set. }); ``` -### goToLastRow(deprecated) +### goToLastRow goToLastRow(): boolean Moves the cursor to the last row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToLastRow](#gotolastrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -781,23 +221,19 @@ Moves the cursor to the last row of the result set. }); ``` -### goToNextRow(deprecated) +### goToNextRow goToNextRow(): boolean Moves the cursor to the next row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToNextRow](#gotonextrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -812,23 +248,19 @@ Moves the cursor to the next row in the result set. }); ``` -### goToPreviousRow(deprecated) +### goToPreviousRow goToPreviousRow(): boolean Moves the cursor to the previous row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToPreviousRow](#gotopreviousrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -843,29 +275,25 @@ Moves the cursor to the previous row in the result set. }); ``` -### getBlob(deprecated) +### getBlob getBlob(columnIndex: number): Uint8Array Obtains the value in the specified column in the current row as a byte array. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getBlob](#getblob9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| Uint8Array | Value in the specified column as a byte array.| + | Type| Description| + | -------- | -------- | + | Uint8Array | Value in the specified column as a byte array.| **Example** @@ -873,29 +301,25 @@ Obtains the value in the specified column in the current row as a byte array. const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` -### getString(deprecated) +### getString getString(columnIndex: number): string Obtains the value in the specified column in the current row as a string. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getString](#getstring9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Value in the specified column as a string.| + | Type| Description| + | -------- | -------- | + | string | Value in the specified column as a string.| **Example** @@ -903,29 +327,25 @@ Obtains the value in the specified column in the current row as a string. const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` -### getLong(deprecated) +### getLong getLong(columnIndex: number): number Obtains the value in the specified column in the current row as a Long. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getLong](#getlong9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a Long.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a Long.| **Example** @@ -933,29 +353,25 @@ Obtains the value in the specified column in the current row as a Long. const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` -### getDouble(deprecated) +### getDouble getDouble(columnIndex: number): number Obtains the value in the specified column in the current row as a double. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDouble](#getdouble9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a double.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a double.| **Example** @@ -963,29 +379,25 @@ Obtains the value in the specified column in the current row as a double. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### isColumnNull(deprecated) +### isColumnNull isColumnNull(columnIndex: number): boolean Checks whether the value in the specified column of the current row is null. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isColumnNull](#iscolumnnull9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the value is null; returns **false** otherwise.| **Example** @@ -993,16 +405,12 @@ Checks whether the value in the specified column of the current row is null. const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` -### close(deprecated) +### close close(): void Closes this result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [close](#close9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md index 846f3f15481d700da9d738857bc217c64cbe6ac9..009ff71b091c7d91a92d92364450316e3aeecfa2 100644 --- a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md +++ b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md @@ -1,4 +1,4 @@ -# @ohos.data.ValuesBucket +# @ohos.data.ValuesBucket (Value Bucket) The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. @@ -34,6 +34,6 @@ Defines the types of the key and value in a KV pair. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core -| Key Type | Value Type | -| ------------- | --------------------------------------------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | +| Key Type | Value Type | +| ------------- | --------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md index 81308054abd5ef5f55ad9d4c78b52f427c16792c..9c3e0e6c94da1406b29e69e27cb68595c2225dd4 100644 --- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -1,4 +1,4 @@ -# Distributed KV Store +# @ohos.data.distributedKVStore (Distributed KV Store) The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. @@ -2395,7 +2395,7 @@ Writes data to this single KV store. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write.| +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Error codes** @@ -2447,7 +2447,7 @@ Write data to this KV store. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write. | +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write. | **Return value** diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index 6aa752374b38735bc3ace8cac13f7d76708b7e66..2a6c9e6c8670b70ce80b59b6eea5cf5defa98234 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -1,4 +1,4 @@ -# @ohos.faultLogger +# @ohos.faultLogger (Fault Logger) The **faultLogger** module implements fault logging functions. diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md index 778fb02db02c051985c50e9325943ff31a12afc1..e102353bf8b19431fab51151c9c634916fa39ff4 100644 --- a/en/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -1,4 +1,4 @@ -# @ohos.geoLocationManager +# @ohos.geoLocationManager (Geolocation Manager) The **geoLocationManager** module provides location service management functions. diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index a5c7034c0333cb640dbe1a51b7f5f6e6f63743ca..86b62bd76ff14cdd0aaa46d60f532b2b52220e4d 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,10 +1,11 @@ -# Geolocation +# @ohos.geolocation (Geolocation) -The Geolocation module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. +The **geolocation** module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. > **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. -> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. +> +> - 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. +> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. ## Applying for Permissions diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index 24125f48cde82856302fc0b981b707c53387d54b..260c8c541809f723cee63a3cf7f7ce9374ff886d 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -1,4 +1,4 @@ -# HiAppEvent +# @ohos.hiAppEvent (Application Event Logging) The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 5d122910002cfc228d009f3468c4b82d21d4e846..3a5687e9ee0b31e29450d72ad7f618a128b30050 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -1,4 +1,4 @@ -# @ohos.hichecker +# @ohos.hichecker (HiChecker) The **hichecker** module is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 3bab9f0be3145354d784d3b3a89cf7054037dcf8..189d855e894451790976eee2c3816cf17ae950b9 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,4 +1,4 @@ -# @ohos.hidebug +# @ohos.hidebug (HiDebug) The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index 01dbef8ce6e24f53485c8b0a780bf1872c5e7963..54355b12b723cf9cad06f5a4064568d5d772bea5 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,4 +1,4 @@ -# @ohos.hilog +# @ohos.hilog (HiLog) The **hilog** module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md index 17f888aca89c40458c7de2ba1344beb48b0d1286..b72b026ce908bbde85e385f46212d32e4a7fd61b 100644 --- a/en/application-dev/reference/apis/js-apis-hitracechain.md +++ b/en/application-dev/reference/apis/js-apis-hitracechain.md @@ -1,4 +1,4 @@ -# @ohos.hiTraceChain (Distributed Call Chain Tracing) +# @ohos.hiTraceChain (Distributed Call Chain Tracing) The **hiTraceChain** module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points. diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md index 9179b9a2f079e3bf719c71827fa820ac35e0b61c..86e09db17bda0e6efa68bbeeb973a26f4a4ff467 100644 --- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -1,4 +1,4 @@ -# @ohos.hiviewdfx.hiAppEvent +# @ohos.hiviewdfx.hiAppEvent (Application Event Logging) The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index c2d5a421c87595094308e70c3bf317c8572b37bf..4de59dd1322f1cc83203ad38bc63746c81d56e8a 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.inputConsumer +# @ohos.multimodalInput.inputConsumer (Input Consumer) The **inputConsumer** module implements listening for combination key events. diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index 2f286827a664af0d8dff2e7c8d133ca97f5e0ab7..c131d9bbd3e50790624d4eca0ea41c94d7022dd2 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -1,16 +1,12 @@ -# @ohos.multimodalInput.inputDevice - +# @ohos.multimodalInput.inputDevice (Input Device) The **inputDevice** module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse. - > **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 - ```js import inputDevice from '@ohos.multimodalInput.inputDevice'; ``` diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md index f7eec22c115ee6e23263fce286973a3832efc3d5..d2d55fa57ee6bd71288d03aa3f42e24bebb80bea 100644 --- a/en/application-dev/reference/apis/js-apis-inputevent.md +++ b/en/application-dev/reference/apis/js-apis-inputevent.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.inputEvent +# @ohos.multimodalInput.inputEvent (Input Event) The **inputEvent** module describes basic events reported by an input device. diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index dbd66538a80290886a1f1cc86ed6b6daea679b41..354f10e3802d163343b658bef56ab4e03689d2c3 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.inputEventClient (Key Injection) +# @ohos.multimodalInput.inputEventClient (Key Event Injection) The **inputEventClient** module implements injection of key events. diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 7bd41f5d0be2922df090f71651b1c4a15aafecb1..304fa76946de0e4279be5095bd1dae46f79c7ca6 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,11 +1,10 @@ -# Input Monitor +# @ohos.multimodalInput.inputMonitor (Input Monitor) -The Input Monitor module implements listening for events of input devices (namely, touchscreen and mouse). +The **inputMonitor** module implements listening for events of input devices (namely, touchscreen and mouse). > **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. -> > - The APIs provided by this module are system APIs. diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index 6f5ff70edc6cdcbb7fcc3a5ce90432eaaf6b312c..e69775942629948eab964f4f91795ddfe7dfeda7 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.keyCode +# @ohos.multimodalInput.keyCode (Key Code) The **keyCode** module provides keycodes for a key device. diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index 6d65e9bfe403d380d354b8cefa981204a4102a46..32c18a558572b8f971b8faf6277c3300e86f9649 100644 --- a/en/application-dev/reference/apis/js-apis-keyevent.md +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.keyEvent +# @ohos.multimodalInput.keyEvent (Key Event) The **keyEvent** module provides key events reported by an input device. diff --git a/en/application-dev/reference/apis/js-apis-mouseevent.md b/en/application-dev/reference/apis/js-apis-mouseevent.md index 81403eff20f8dd8c21d0b7b30bf0989c146de455..92935d6f31e788eb0b71ec6529fbc94264e3d8d1 100644 --- a/en/application-dev/reference/apis/js-apis-mouseevent.md +++ b/en/application-dev/reference/apis/js-apis-mouseevent.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.mouseEvent +# @ohos.multimodalInput.mouseEvent (Mouse Event) The **mouseEvent** module provides mouse events reported by an input device. diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 5df384d16ab9e802971b36cc2527ab36538f143f..d5a5f1585a5ae153694833b611861cc49325c4e7 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -1,4 +1,4 @@ -# # @ohos.net.connection +# @ohos.net.connection (Network Connection Management) The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index 924d8157a82c8125506cf3a995c1d934cce2c7cc..d41845ec1859507bb96a071dff2a57e16f4cf12b 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -1,4 +1,4 @@ -# @ohos.net.ethernet +# @ohos.net.ethernet (Ethernet Connection Management) The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index a688bf46448c6371ba5c0bd2e740ed276c0bbe20..144ffa9c6e2d405c83e7cf14fdb7278c616759d3 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,4 +1,4 @@ -# @ohos.net.sharing +# @ohos.net.sharing (Network Sharing) The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index ad7d19b4ab7a3cfa6593c81f2c70b52f403aa4d1..ae5b7999bd7e579179920a73fcaea6116890ff70 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -1,6 +1,6 @@ -# Observer +# @ohos.telephony.observer (Observer) -The observer module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. +The **observer** module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index c6888254790880a4e310564f5d9faccc00d2778c..fc74447111636244fb54e604dba5c458a6e6e061 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.pointer +# @ohos.multimodalInput.pointer (Mouse Pointer) The **pointer** module provides APIs related to pointer attribute management. @@ -121,9 +121,13 @@ Checks the visible status of the mouse pointer. This API uses a promise to retur **Example** ```js -pointer.isPointerVisible().then((visible) => { - console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); -}); +try { + pointer.isPointerVisible().then((visible) => { + console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); + }); +} catch (error) { + console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` ## pointer.setPointerSpeed9+ diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index f1a94349e34b8892fe0d96cebc25b5485514e92a..4dc07d44197a78f01cb3e9018293cc1da88bea38 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -1,4 +1,4 @@ -# @ohos.power +# @ohos.power (System Power Management) The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status. diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index cf518ed93a2aea668985ae96031b12d48e284811..4d7ffb05e886f6b908a771b091f83983452bcfed 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -1,4 +1,4 @@ -# Privacy Management +# @ohos.privacyManager (Privacy Management) The **privacyManager** module provides APIs for privacy management, such as management of permission usage records. diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 91c6be9cd7d076dbb72a502e64363d729668972f..dfb1dd75061b1bb272170b5dbd7c202d320ce304 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1,6 +1,6 @@ -# Radio +# @ohos.telephony.radio (Network Search) -The radio module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. +The **radio** module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 5d215b54b33730d147c72c7e1e5981710640c543..7dc343709c19421175b4f99e6308c1c0ad90e5dd 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,4 +1,4 @@ -# Resource Manager +# @ohos.resourceManager (Resource Manager) The Resource Manager module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density. diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 94757432a9c16fa471fb98629b63387594542e65..8fc776d5508dccfd04155a3952936743de8e711c 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,6 +1,6 @@ -# @ohos.rpc +# @ohos.rpc (RPC) -The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. +The **rpc** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index 29f70bf59b848b54f23451a8fd34373d4d28db5e..ee70e09ca874602bf8e41f3d4001b61caa5a0344 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,4 +1,4 @@ -# @ohos.runningLock +# @ohos.runningLock (Runninglock) The **runningLock** module provides APIs for creating, querying, holding, and releasing running locks. diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index 9dcef8737df6eec61080fdbc7569ed7d4eb4a238..c726ec7c8fdd4cd6f16d71f5a6892bc565b66cf6 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,4 +1,4 @@ -# @ohos.screenLock +# @ohos.screenLock (Screenlock) The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set. diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 0f5d909e9b038c65bcd353afae633495a9bd2c4b..e9022ac7d23c3f213487da532d92a369c17a5c48 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -1,6 +1,6 @@ -# Screen +# @ohos.screen (Screen) -The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. +The **screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 81c05044174b46f17b6d5224f923167256290e4f..eb88ca8c05459fca0ba2ecd4dfcab60d49677aae 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -1,6 +1,6 @@ -# SIM Management +# @ohos.telephony.sim (SIM Management) -The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. +The **sim** module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index c26311312c5cc2360ddf4f3784f66bba05b0f5b1..901e3b258b7aa73530935baa81a6366f7aa50e65 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -1,6 +1,6 @@ -# SMS +# @ohos.telephony.sms (SMS) -The SMS module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. +The **sms** module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 989cc9985727b1e43c828f354f76a3be8dae492f..bd14137464ce195f5c61b9d6a53ce6ef79cd3f10 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,4 +1,4 @@ -# @ohos.net.socket +# @ohos.net.socket (Socket Connection) The **socket** module implements socket connection management and operation. diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 86675315d63423d728d2db90afd6b049614ee80a..c54d9d4b01fec93df43f92f47eab8aaae951fb4e 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -1,4 +1,4 @@ -# App Storage Statistics +# @ohos.storageStatistics (App Storage Statistics) The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md index 31959da80f23b90f54ea10883417eec202152d1a..d673a500027654075ff330c916cd22add25abaf6 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -1,6 +1,6 @@ -# Battery Info +# @system.battery (Battery Information) -This module allows you to query the charging status and remaining power of a device. +The **battery** module allows you to query the charging status and remaining power of a device. > **NOTE** > - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md index 2773c74397046c44784b65cc458be75eef8c21ea..939e7d7021bc8f93ad7359004de58f525feeee05 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,6 +1,6 @@ -# Screen Brightness +# @system.brightness (Screen Brightness) -This module provides APIs for querying and adjusting the screen brightness and mode. +The **brightness** module provides APIs for querying and adjusting the screen brightness and mode. > **NOTE** > - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-system-capability.md b/en/application-dev/reference/apis/js-apis-system-capability.md new file mode 100644 index 0000000000000000000000000000000000000000..7949bae9880af5a8e428e62440595a4a6e990da7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-capability.md @@ -0,0 +1,79 @@ +# @ohos.systemCapability (SystemCapability) + +System capability (SysCap) refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. This module provides APIs for querying the set of system capabilities. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. + + +## Modules to Import + +```ts +import systemcapability from '@ohos.systemCapability' +``` + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(callback: AsyncCallback): void; + +Queries system capabilities. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Developtools.Syscap + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback | Yes| Callback invoked to return the result.| + + +**Example** + +```ts +try { + systemcapability.querySystemCapabilities(function (err, data) { + if (err == undefined) { + console.log("get system capabilities:" + data) + } else { + console.log(" get system capabilities err:" + err.code) + }}); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(): Promise<string> + +Queries system capabilities. This API uses a promise to return the result. + +**System capability**: SystemCapability.Startup.SystemInfo + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the result.| + +**Example** + +```ts +try { + var p = systemcapability.querySystemCapabilities(); + p.then(function (value) { + console.log("get system capabilities: " + value); + }).catch(function (err) { + console.log("get system capabilities error: " + err.code); + }); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +> **NOTE** +> - The system capabilities returned by the preceding APIs are in the form of an encoded numeric string. diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index 6812d87828d55851d375eadba9dab6b2de55560a..dddb6a685f00a8a5a1829e489d43af4a198bdffa 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,6 +1,6 @@ -# Encryption Algorithm +# @system.cipher (Cipher Algorithm) -> **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -31,7 +31,7 @@ Defines the input parameters of **cipher.rsa()**. | Name | Type | Mandatory| Description | | -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.| -| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.| +| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length.
For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding. | | key | string | Yes | RSA key. It is a public key in encryption and a private key in decryption. | | transformation | string | No | RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| | success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. | diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index e9b54c774d2bc1e43de0dd7edb55e47bcf9c3b57..f1c9ad362175bd709d27bc4c7aec0059b413221e 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -1,6 +1,6 @@ -# Cellular Data +# @ohos.telephony.data (Cellular Data) -The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. +The **data** module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index a8e25a0149aa8d6257363db0321a563cfaa81eb6..514e7062cd649d8bf5b92261bceeb7cbed870166 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -1,4 +1,4 @@ -# @ohos.thermal +# @ohos.thermal (Thermal Management) The **thermal** module provides thermal level-related callback and query APIs to obtain the information required for thermal control. diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md index 54b4eb2aa3aa9922867abb82cb11737995751a81..ae49b428e00c4c22ed126ecc539290a692b69696 100644 --- a/en/application-dev/reference/apis/js-apis-touchevent.md +++ b/en/application-dev/reference/apis/js-apis-touchevent.md @@ -1,4 +1,4 @@ -# @ohos.multimodalInput.touchEvent +# @ohos.multimodalInput.touchEvent (Touch Event) The **touchEvent** module provides touch events reported by an input device. diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 412623cd7bf7d9a8fb55a17499bea8327d84f91a..ffb07ba4f21cc5f154bcf25062f86845c97577dc 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -1,4 +1,4 @@ -# @ohos.update +# @ohos.update (Update) The **update** module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md index b3be9875df2554c6df5b8c358c9243d734d87874..68a127a08bdfd1df0ca558866dc3cde577e2b25a 100644 --- a/en/application-dev/reference/apis/js-apis-usb-deprecated.md +++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -1,8 +1,8 @@ -# USB +# @ohos.usb (USB Management) -The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. +The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. -> **NOTE** +> **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. diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index db5f65e888e6b40a07362bc74a8c2375d6bf22f2..9035d2d040209f44a019fb69b3da6edc49b481b3 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,4 +1,4 @@ -# @ohos.usbV9 +# @ohos.usbV9 (USB Management) The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md index 9a45d1fe8f9644f0072fdfdb44c31f66c19e3d59..7005776c804fa21fe899f82d29253c2436b4f5ea 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -1,4 +1,4 @@ -# Facial Authentication +# @ohos.userIAM.faceAuth (Facial Authentication) The **userIAM.faceAuth** module provides APIs for face enrollment. @@ -34,17 +34,17 @@ A constructor used to create a **FaceAuthManager** object. **Example** - ```js - import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; - let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); - ``` +let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); +``` ### setSurfaceId setSurfaceId(surfaceId: string): void; -Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. +Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. This API must be used with [AddCredential](./js-apis-osAccount.md#addcredential8). **System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth @@ -56,17 +56,28 @@ Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#ge | -------------- | ---------------------------------- | ---- | -------------------------- | | surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| +For details about the following error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 12700001 | The operation is failed. | + **Example** - ```js - import faceAuth from '@ohos.userIAM.faceAuth'; - - let surfaceId = "123456"; - let manager = new faceAuth.FaceAuthManager(); - try { - manager.setSurfaceId(surfaceId); - console.info("Set the surface ID successfully"); - } catch (e) { - console.error("Failed to set the surface ID, error = " + e); - } - ``` +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + +// The surfaceId is obtained from the XComponent control. The surfaceId here is only an example. +let surfaceId = "123456"; +let manager = new userIAM_faceAuth.FaceAuthManager(); +try { + manager.setSurfaceId(surfaceId); + console.info("Set the surface ID successfully"); +} catch (e) { + console.error("Failed to set the surface ID, error = " + e); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index ce73ba0bcd0ed53bb75bcb873cf35dd8f6910f6d..29044d135b43286a8b3df624584750022f6576b8 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -1,4 +1,4 @@ -# User Authentication +# @ohos.userIAM.userAuth (User Authentication) The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login. @@ -12,268 +12,115 @@ The **userIAM.userAuth** module provides user authentication capabilities in ide import userIAM_userAuth from '@ohos.userIAM.userAuth'; ``` -## Sample Code - -```js -// API version 9 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; - -export default { - getVersion() { - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - }, - - start() { - console.info("start auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - console.log("authV9 result " + result.result); - console.log("authV9 token " + result.token); - console.log("authV9 remainAttempts " + result.remainAttempts); - console.log("authV9 lockoutDuration " + result.lockoutDuration); - } - }); - // If tips are needed - auth.on("tip", { - callback : (result : userIAM_userAuth.TipInfo) => { - switch (result.tip) { - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: - // Do something; - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: - // Do something; - // ... - default: - // Do others. - } - } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - }, +## AuthResultInfo9+ - getAvailableStatus() { - console.info("start check auth support"); - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - }, +Defines the authentication result. - cancel() { - console.info("start cancel auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +**System capability**: SystemCapability.UserIAM.UserAuth.Core - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| result | number | Yes | Authentication result. | +| token | Uint8Array | No | Token that has passed the user identity authentication.| +| remainAttempts | number | No | Number of remaining authentication times allowed.| +| lockoutDuration | number | No | Time for which the authentication operation is frozen.| -```js -// API version 8 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; -let auth = new userIAM_userAuth.UserAuth(); +## TipInfo9+ -export default { - getVersion() { - console.info("start get version"); - let version = auth.getVersion(); - console.info("auth version = " + version); - }, - - startAuth() { - console.info("start auth"); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - }, - - checkAuthSupport() { - console.info("start check auth support"); - let checkCode = this.auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - }, - - cancelAuth() { - console.info("start cancel auth"); - // Obtain contextId using auth(). - let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - console.info("auth onResult result = " + result); - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - console.info("auth onAcquireInfo module = " + module); - } - }); - let cancelCode = this.auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - } -} -``` +Defines the authentication tip information. -```js -// API version 6 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; +**System capability**: SystemCapability.UserIAM.UserAuth.Core -export default { - startAuth() { - console.info("start auth"); - let auth = userIAM_userAuth.getAuthenticator(); - auth.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - // Add the logic to be executed when the authentication is successful. - }).catch((code)=>{ - console.error("auth fail, code = " + code); - // Add the logic to be executed when the authentication fails. - }); - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| module | number | Yes | ID of the module that sends the tip information. | +| tip | number | Yes | Tip to be given during the authentication process. | ## EventInfo9+ -Defines the event information used in authentication. +Enumerates the authentication event information types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Type | Description | +| Value | Description | | --------- | ----------------------- | -| [AuthResultInfo](#authresultinfo9) | Authentication result information. | +| [AuthResultInfo](#authresultinfo9) | Authentication result. | | [TipInfo](#tipinfo9) | Authentication tip information. | +## AuthEventKey9+ + +Defines the keyword of the authentication event type. It is used as a parameter of [on](#on9). + +| Value | Description | +| ---------- | ----------------------- | +| "result" | If the first parameter of [on](#on9) is **result**, the [callback](#callback9) returns the authentication result.| +| "tip" | If the first parameter of [on](#on9) is **tip**, the [callback](#callback9) returns the authentication tip information.| + ## AuthEvent9+ -Provides callbacks to return authentication events. +Provides an asynchronous callback to return the authentication event information. ### callback9+ -callback: (result : EventInfo) => void +callback(result : EventInfo) : void -Called to return the authentication result or authentication tips. +Called to return the authentication result or authentication tip information. **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | -------------------------------------------------------- | -| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------ | +| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +// Obtain the authentication result through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` - -## AuthResultInfo9+ - -Defines the authentication result information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| result | number | Yes | Authentication result. | -| token | Uint8Array | No | Token that has passed the user identity authentication.| -| remainAttempts | number | No | Number of remaining authentication times allowed.| -| lockoutDuration | number | No | Time for which the authentication operation is frozen.| - -## TipInfo9+ - -Defines the authentication tip information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| module | number | No | Authentication module. | -| tip | number | No | Tip to be given during the authentication process. | - -## AuthEventKey9+ - -Defines the keyword of an authentication event. - -| Value | Description | -| ---------- | ----------------------- | -| "result" | Indicates authentication result.| -| "tip" | If **AuthEventKey** is **result**, the callback returns the authentication tip information.| + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +// Obtain the authentication tip information through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("tip", { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // Do something; + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // Do something. + default: + // Do others. + } + } + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ## AuthInstance9+ @@ -281,9 +128,12 @@ Implements user authentication. ### on9+ -on(name : AuthEventKey, callback : AuthEvent) : void +on : (name : AuthEventKey, callback : AuthEvent) => void -Enables authentication event listening. +Subscribes to the user authentication events of the specified type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to subscribe to events. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -291,151 +141,210 @@ Enables authentication event listening. | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event to listen for. | -| callback | AuthEvent | Yes | Callback invoked to return the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Authentication event type. If the value is **result**, the callback returns the authentication result. If the value is **tip**, the callback returns the authentication tip information.| +| callback | [AuthEvent](#authevent9) | Yes | Callback invoked to return the authentication result or tip information.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - // If tips are needed - auth.on("tip", { + }); + // Subscribe to authentication tip information. + auth.on("tip", { callback : (result : userIAM_userAuth.TipInfo) => { switch (result.tip) { case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: // Do something; case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: // Do something; - // ... default: // Do others. } } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ### off9+ -off(name : AuthEventKey) : void +off : (name : AuthEventKey) => void -Disables authentication event listening. +Unsubscribes from the user authentication events of the specific type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to unsubscribe from events. **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Type of the authentication event to unsubscribe from. If the value is **result**, the authentication result is unsubscribed from. If the value is **tip**, the authentication tip information is unsubscribed from.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let auth; +try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); +} catch (error) { + console.log("get auth instance failed" + error); +} - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +try { + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - console.log("turn on authentication event listening success"); - } catch (error) { - console.log("turn off authentication event listening failed " + error); - // do error - } - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.off("result"); - console.info("turn off authentication event listening success"); - } catch (error) { - console.info("turn off authentication event listening failed, error = " + error); - } - ``` + }); + console.log("subscribe authentication event success"); +} catch (error) { + console.log("subscribe authentication event failed " + error); +} +// Unsubscribe from the authentication result. +try { + auth.off("result"); + console.info("cancel subscribe authentication event success"); +} catch (error) { + console.info("cancel subscribe authentication event failed, error = " + error); +} +``` ### start9+ -start() : void +start : () => void Starts authentication. +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500001 | Authentication failed. | +| 12500002 | General operation error. | +| 12500003 | The operation is canceled. | +| 12500004 | The operation is time-out. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500007 | The authentication task is busy. | +| 12500009 | The authenticator is locked. | +| 12500010 | The type of credential has not been enrolled. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.start(); + console.info("authV9 start auth success"); +} catch (error) { + console.info("authV9 start auth failed, error = " + error); +} +``` ### cancel9+ -cancel(): void +cancel : () => void -Cancels the authentication. +Cancels this authentication. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. The [AuthInstance](#authinstance9) instance must be the one being authenticated. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.cancel(); + console.info("cancel auth success"); +} catch (error) { + console.info("cancel auth failed, error = " + error); +} +``` ## userIAM_userAuth.getAuthInstance9+ @@ -444,7 +353,7 @@ getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel Obtains an **AuthInstance** instance for user authentication. > **NOTE**
-> Each **AuthInstance** can be used to initiate an authentication only once. +> An **AuthInstance** instance can be used for an authentication only once. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -460,23 +369,35 @@ Obtains an **AuthInstance** instance for user authentication. | Type | Description | | ----------------------------------------- | ------------ | -| [AuthInstance](#authinstance9) | **Authenticator** object obtained.| +| [AuthInstance](#authinstance9) | **Authenticator** instance obtained.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - console.info("get auth instance success"); - } catch (error) { - console.info("get auth instance success failed, error = " + error); - } - ``` +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.info("get auth instance success"); +} catch (error) { + console.info("get auth instance success failed, error = " + error); +} +``` ## userIAM_userAuth.getVersion9+ @@ -494,24 +415,33 @@ Obtains the version of this authenticator. | ------ | ---------------------- | | number | Authenticator version obtained.| +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - ``` +try { + let version = userIAM_userAuth.getVersion(); + console.info("auth version = " + version); +} catch (error) { + console.info("get version failed, error = " + error); +} +``` ## userIAM_userAuth.getAvailableStatus9+ getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void -Checks whether the authentication capability of the specified trust level is available. +Checks whether the specified authentication capability is supported. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -522,54 +452,65 @@ Checks whether the authentication capability of the specified trust level is ava | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500010 | The type of credential has not been enrolled. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - ``` +try { + userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + console.info("current auth trust level is supported"); +} catch (error) { + console.info("current auth trust level is not supported, error = " + error); +} +``` - ## ResultCodeV99+ +## UserAuthResultCode9+ -Enumerates the operation results. +Enumerates the authentication result codes. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------- | ------ | -------------------- | -| SUCCESS | 12500000 | The operation is successful. | -| FAIL | 12500001 | The operation failed. | -| GENERAL_ERROR | 12500002 | A common operation error occurred. | -| CANCELED | 12500003 | The operation is canceled. | -| TIMEOUT | 12500004 | The operation timed out. | +| SUCCESS | 12500000 | The authentication is successful. | +| FAIL | 12500001 | The authentication failed. | +| GENERAL_ERROR | 12500002 | A general operation error occurred. | +| CANCELED | 12500003 | The authentication is canceled. | +| TIMEOUT | 12500004 | The authentication timed out. | | TYPE_NOT_SUPPORT | 12500005 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 12500006 | The authentication trust level is not supported. | | BUSY | 12500007 | Indicates the busy state. | -| INVALID_PARAMETERS | 12500008 | Invalid parameters are detected. | | LOCKED | 12500009 | The authentication executor is locked. | | NOT_ENROLLED | 12500010 | The user has not entered the authentication information.| ## UserAuth8+ -Provides methods to manage an **Authenticator** object. +Provides APIs to manage an **Authenticator** object. ### constructor(deprecated) constructor() -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). +A constructor used to create an authenticator instance. -A constructor used to create an **authenticator** object. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -577,25 +518,24 @@ A constructor used to create an **authenticator** object. | Type | Description | | ---------------------- | -------------------- | -| [UserAuth](#userauth8) | **Authenticator** object obtained.| +| [UserAuth](#userauth8) | **Authenticator** instance obtained.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - ``` +let auth = new userIAM_userAuth.UserAuth(); +``` ### getVersion(deprecated) getVersion() : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). +Obtains the version of this authenticator. -Obtains the authentication executor version. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -609,23 +549,22 @@ Obtains the authentication executor version. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - let version = auth.getVersion(); - console.info("auth version = " + version); - ``` +let auth = new userIAM_userAuth.UserAuth(); +let version = auth.getVersion(); +console.info("auth version = " + version); +``` ### getAvailableStatus(deprecated) getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). +Checks whether the specified authentication capability is supported. -Obtains the available status of the specified authentication trust level. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -636,40 +575,37 @@ Obtains the available status of the specified authentication trust level. | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Available status obtained. For details, see [ResultCode](#resultcodedeprecated).| +| number | Query result. If the authentication capability is supported, **SUCCESS** is returned. Otherwise, a [ResultCode](#resultcodedeprecated) is returned.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); +if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("check auth support success"); +} else { + console.error("check auth support fail, code = " + checkCode); +} +``` ### auth(deprecated) auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9). - Performs user authentication. This API uses a callback to return the result. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9). + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -680,8 +616,8 @@ Performs user authentication. This API uses a callback to return the result. | -------------- | ---------------------------------------- | ---- | ------------------------ | | challenge | Uint8Array | Yes | Challenge value, which can be null. | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | -| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | +| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | **Return value** @@ -691,36 +627,35 @@ Performs user authentication. This API uses a callback to return the result. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### cancelAuth(deprecated) cancelAuth(contextID : Uint8Array) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). +Cancels an authentication based on the context ID. -Cancels an authentication. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -730,100 +665,86 @@ Cancels an authentication. | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | Yes | Context ID, which is obtained by using [auth](#authdeprecated).| +| contextID | Uint8Array | Yes | Context ID, which is obtained by [auth](#authdeprecated).| **Return value** | Type | Description | | ------ | ------------------------ | -| number | Whether the authentication is canceled.| +| number | Returns **SUCCESS** if the cancellation is successful. Returns a [ResultCode](#resultcodedeprecated) otherwise.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - // contextId can be obtained using auth(). In this example, it is defined here. - let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); - let auth = new userIAM_userAuth.UserAuth(); - let cancelCode = auth.cancelAuth(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +// contextId can be obtained by auth(). In this example, it is defined here. +let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); +let auth = new userIAM_userAuth.UserAuth(); +let cancelCode = auth.cancelAuth(contextId); +if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("cancel auth success"); +} else { + console.error("cancel auth fail"); +} +``` ## IUserAuthCallback(deprecated) -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). +Provides callbacks to return the authentication result. -Defines the object of the result returned by the callback during authentication. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). ### onResult(deprecated) onResult: (result : number, extraInfo : AuthResult) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to return the authentication result. -Obtains the authentication result. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | ------------------------------------------------------------ | -| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated). | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------------------------ | +| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated).| | extraInfo | [AuthResult](#authresultdeprecated) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| - **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### onAcquireInfo(deprecated) onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to acquire authentication tip information. This API is optional. -Obtains the tip code information during authentication. This function is optional. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -831,89 +752,74 @@ Obtains the tip code information during authentication. This function is optiona | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------ | -| module | number | Yes | Type of the authentication executor. | -| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| +| module | number | Yes | ID of the module that sends the tip information. | +| acquire | number | Yes | Authentication tip information.| | extraInfo | any | Yes | Reserved field. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; -## AuthResult(deprecated) +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } +}); +``` -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). +## AuthResult(deprecated) Represents the authentication result object. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). + **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| token | Uint8Array | No | Identity authentication token. | +| ------------ | ---------- | ---- | -------------------| +| token | Uint8Array | No | Authentication token information.| | remainTimes | number | No | Number of remaining authentication operations.| | freezingTime | number | No | Time for which the authentication operation is frozen.| ## ResultCode(deprecated) -> **NOTE**
-> This object is deprecated since API version 9. You are advised to use [ResultCodeV9](#resultcodev99). +Enumerates the authentication result codes. -Enumerates the operation results. +> **NOTE**
+> This object is deprecated since API version 9. You are advised to use [UserAuthResultCode](#userauthresultcode9). **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------- | ------ | -------------------- | | SUCCESS | 0 | The operation is successful. | -| FAIL | 1 | The operation failed. | -| GENERAL_ERROR | 2 | A common operation error occurred. | -| CANCELED | 3 | The operation is canceled. | -| TIMEOUT | 4 | The operation timed out. | +| FAIL | 1 | The authentication failed. | +| GENERAL_ERROR | 2 | A general operation error occurred. | +| CANCELED | 3 | The authentication is canceled. | +| TIMEOUT | 4 | The authentication timed out. | | TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | | BUSY | 7 | Indicates the busy state. | +| INVALID_PARAMETERS | 8 | Invalid parameters are detected. | | LOCKED | 9 | The authentication executor is locked. | | NOT_ENROLLED | 10 | The user has not entered the authentication information.| - ## FaceTips8+ Enumerates the tip codes used during the facial authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------------- | ------ | ------------------------------------ | | FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. | | FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. | @@ -934,7 +840,7 @@ Enumerates the tip codes used during the fingerprint authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------------------------- | ------ | -------------------------------------------------- | | FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | | FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| @@ -950,7 +856,7 @@ Enumerates the identity authentication types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------- | ------ | ---------- | | FACE | 2 | Facial authentication.| | FINGERPRINT | 4 | Fingerprint authentication.| @@ -961,7 +867,7 @@ Enumerates the trust levels of the authentication result. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name| Default Value| Description | +| Name| Value | Description | | ---- | ------ | ------------------------- | | ATL1 | 10000 | Trust level 1.| | ATL2 | 20000 | Trust level 2.| @@ -972,18 +878,18 @@ Enumerates the trust levels of the authentication result. getAuthenticator(): Authenticator +Obtains an **Authenticator** instance for user authentication. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [constructor](#constructordeprecated). -Obtains an **Authenticator** object for user authentication. - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** | Type | Description | | ----------------------------------------- | ------------ | -| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| +| [Authenticator](#authenticatordeprecated) | **Authenticator** instance obtained.| **Example** ```js @@ -992,61 +898,61 @@ Obtains an **Authenticator** object for user authentication. ## Authenticator(deprecated) +Defines the **Authenticator** object. + > **NOTE**
> This object is deprecated since API version 8. You are advised to use [UserAuth](#userauth8). -Provides methods to manage an **Authenticator** object. - - ### execute(deprecated) execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void +Performs user authentication. This API uses asynchronous callback to return the result. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses asynchronous callback to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------- | | type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| -| callback | AsyncCallback<number> | No | Callback used to return the result. | +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | - Parameters returned in callback +Parameters returned in callback | Type | Description | | ------ | ------------------------------------------------------------ | | number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ - if (code === userIAM_userAuth.ResultCode.SUCCESS) { - console.info("auth success"); - return; - } - console.error("auth fail, code = " + code); - }); - ``` + +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ + if (code === userIAM_userAuth.ResultCode.SUCCESS) { + console.info("auth success"); + return; + } + console.error("auth fail, code = " + code); +}); +``` ### execute(deprecated) -execute(type:AuthType, level:SecureLevel): Promise<number> +execute(type : AuthType, level : SecureLevel): Promise<number> + +Performs user authentication. This API uses a promise to return the result. > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses a promise to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -1066,25 +972,25 @@ Performs user authentication. This API uses a promise to return the result. **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - }).catch((error)=>{ - console.error("auth fail, code = " + error); - }); - ``` +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2").then((code)=>{ + console.info("auth success"); +}).catch((error)=>{ + console.error("auth fail, code = " + error); +}); +``` ## AuthenticationResult(deprecated) +Enumerates the authentication results. + > **NOTE**
> This object is discarded since API version 8. You are advised to use [ResultCode](#resultcodedeprecated). -Enumerates the authentication results. - **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------------ | ------ | -------------------------- | | NO_SUPPORT | -1 | The device does not support the current authentication mode.| | SUCCESS | 0 | The authentication is successful. | diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 8897b51f07b4e00feae752e792820e6b9b32370f..09e3c245326f4bc9008e20535edfa4f0a2c3d2d0 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -1,6 +1,6 @@ -# @ohos.util +# @ohos.util (Utilities) -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. +The **util** module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 660c42d8a3c44b0cb962dce1d5245957f37c5c63..2b2fa3af70da2fd1725ef0221b8fd7cf5654f531 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -1,8 +1,8 @@ -# @ohos.net.webSocket +# @ohos.net.webSocket (WebSocket Connection) The **webSocket** module implements WebSocket connection management and operation. -> **NOTE:**
+> **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. > diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index 92f40c92f26257e614135694d49d69608ea32a23..83d89392cd8ade90901018fbe5721ce53ba54f2e 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -1,6 +1,6 @@ -# @ohos.web.webview (Webview) +# @ohos.web.webview The **Webview** module provides APIs for web control. @@ -19,6 +19,46 @@ The **Webview** module provides APIs for web control. ```ts import web_webview from '@ohos.web.webview'; ``` + +### once + +once(type: string, callback: Callback\): void + +Registers a one-time callback for web events of the specified type. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | -------------------- | +| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | +| headers | Callback\ | Yes | Callback to register.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +web_webview.once("webInited", () => { + console.log("setCookie") + web_webview.WebCookieManager.setCookie("www.example.com", "a=b") +}) + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebMessagePort Implements a **WebMessagePort** object to send and receive messages. @@ -61,7 +101,7 @@ struct WebComponent { ### postMessageEvent -postMessageEvent(message: string): void +postMessageEvent(message: WebMessage): void Sends a message. For the complete sample code, see [postMessage](#postmessage). @@ -71,7 +111,7 @@ Sends a message. For the complete sample code, see [postMessage](#postmessage). | Name | Type | Mandatory| Description | | ------- | ------ | ---- | :------------- | -| message | string | Yes | Message to send.| +| message | [WebMessage](#webmessage) | Yes | Message to send.| **Error codes** @@ -113,7 +153,7 @@ struct WebComponent { ### onMessageEvent -onMessageEvent(callback: (result: string) => void): void +onMessageEvent(callback: (result: WebMessage) => void): void Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). @@ -123,7 +163,7 @@ Registers a callback to receive messages from the HTML5 side. For the complete s | Name | Type | Mandatory| Description | | -------- | -------- | ---- | :------------------- | -| result | string | Yes | Message received.| +| result | [WebMessage](#webmessage) | Yes | Message received.| **Error codes** @@ -152,7 +192,17 @@ struct WebComponent { try { this.ports = this.controller.createWebMessagePorts(); this.ports[1].onMessageEvent((msg) => { - console.log("received message from html5, on message:" + msg); + if (typeof(msg) == "string") { + console.log("received string message from html5, string is:" + msg); + } else if (typeof(msg) == "object") { + if (msg instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + msg.byteLength); + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } }) } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); @@ -166,13 +216,40 @@ struct WebComponent { ## WebviewController -Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs in the **WebviewController** can be invoked only after it has been bound to the target **\** component. +Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\** component. + +### initializeWebEngine + +static initializeWebEngine(): void + +Loads the dynamic link library (DLL) file of the web engine. This API can be called before the **\** component is initialized to improve the startup performance. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +The following code snippet exemplifies calling this API after the EntryAbility is created. + +```ts +// xxx.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import web_webview from '@ohos.web.webview'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("EntryAbility onCreate") + web_webview.WebviewController.initializeWebEngine() + globalThis.abilityWant = want + console.log("EntryAbility onCreate done") + } +} +``` ### Creating an Object ```ts // xxx.ets -import web_webview from '@ohos.web.webview' +import web_webview from '@ohos.web.webview'; @Entry @Component @@ -1397,8 +1474,21 @@ struct WebComponent { // 2. Send one of the message ports to the HTML side, which can then save and use the port. this.controller.postMessage('__init_port__', [this.ports[0]], '*'); // 3. Register a callback for the other message port on the application side. - this.ports[1].onMessageEvent((result: string) => { - var msg = 'Got msg from HTML: ' + result; + this.ports[1].onMessageEvent((result: WebMessage) => { + var msg = 'Got msg from HTML:'; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } this.receivedFromHtml = msg; }) } catch (error) { @@ -1456,7 +1546,21 @@ window.addEventListener('message', function (event) { The h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. h5Port.onmessage = function (event) { // 2. Receive the message sent from the eTS side. - var msg = 'Got message from ets:' + event.data; + var msg = 'Got message from ets:'; + var result = event.data; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } output.innerHTML = msg; } } @@ -1759,7 +1863,7 @@ struct WebComponent { getTitle(): string -Obtains the title of the file selector. +Obtains the title of the current web page. **System capability**: SystemCapability.Web.Webview.Core @@ -1767,7 +1871,7 @@ Obtains the title of the file selector. | Type | Description | | ------ | -------------------- | -| string | Title of the file selector.| +| string | Title of the current web page.| **Error codes** @@ -2123,6 +2227,222 @@ struct WebComponent { } ``` +### scrollTo + +scrollTo(x:number, y:number): void + +Scrolls the page to the specified absolute position. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| +| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollTo') + .onClick(() => { + try { + this.controller.scrollTo(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### scrollBy + +scrollBy(deltaX:number, deltaY:number): void + +Scrolls the page by the specified amount. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| +| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollBy') + .onClick(() => { + try { + this.controller.scrollBy(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### slideScroll + +slideScroll(vx:number, vy:number): void + +Simulates a slide-to-scroll action on the page at the specified velocity. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| +| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('slideScroll') + .onClick(() => { + try { + this.controller.slideScroll(500, 500); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + ### getOriginalUrl getOriginalUrl(): string @@ -2244,7 +2564,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 401 | Invalid input parameter. | **Example** @@ -2275,7 +2594,7 @@ struct WebComponent { ### hasImage -hasImage(callback: AsyncCallback): void +hasImage(callback: AsyncCallback\): void Checks whether this page contains images. This API uses an asynchronous callback to return the result. @@ -2294,7 +2613,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 401 | Invalid input parameter. | **Example** @@ -2312,7 +2630,7 @@ struct WebComponent { Button('hasImageCb') .onClick(() => { try { - this.controller.hasImage((err, data) => { + this.controller.hasImage((error, data) => { if (error) { console.info(`hasImage error: ` + JSON.stringify(error)) return; @@ -2331,7 +2649,7 @@ struct WebComponent { ### hasImage -hasImage(): Promise +hasImage(): Promise\ Checks whether this page contains images. This API uses a promise to return the result. @@ -2350,7 +2668,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 401 | Invalid input parameter. | **Example** @@ -2396,7 +2713,7 @@ Clears the cache in the application. This API will clear the cache for all webvi | Name | Type | Mandatory| Description | | -------- | ------- | ---- | -------------------------------------------------------- | -| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **false** means to only clear the cache in the RAM.| +| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **true** means to clear the cache in the ROM and RAM at the same time, and **false** means to only clear the cache in the RAM.| **Error codes** @@ -2405,7 +2722,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 401 | Invalid input parameter. | **Example** @@ -2483,9 +2799,58 @@ struct WebComponent { } ``` +### customizeSchemes + +static customizeSchemes(schemes: Array\): void + +Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\** component is initialized. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | -------------------------------------- | +| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + responseweb: WebResourceResponse = new WebResourceResponse() + scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true} + scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true} + scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true} + + aboutToAppear():void { + try { + web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]) + } catch(error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + } + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onInterceptRequest((event) => { + console.log('url:' + event.request.getRequestUrl()) + return this.responseweb + }) + } + } +} +``` + ## WebCookieManager -Implements a **WebCookie** object to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookie** object. +Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. ### getCookie @@ -3600,7 +3965,7 @@ Implements a **WebAsyncController** object, which can be used to control the beh @Component struct WebComponent { controller: WebController = new WebController(); - webAsyncController: WebAsyncController = new web_webview.WebAsyncController(this.controller) + webAsyncController: web_webview.WebAsyncController = new web_webview.WebAsyncController(this.controller) build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -3635,8 +4000,8 @@ Stores this web page. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | | callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise.| **Example** @@ -3677,14 +4042,14 @@ Stores this web page. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise | Promise used to return the save path if the operation is successful and null otherwise.| +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the save path if the operation is successful and null otherwise. | **Example** @@ -4100,6 +4465,15 @@ Provides the element information of the area being clicked. For details about th | type | [HitTestTypeV9](#hittesttypev9) | Yes| No| Element type of the area being clicked.| | extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.| +## WebMessage + +Describes the data types supported for [WebMessagePort](#webmessageport). + +| Type | Description | +| -------- | -------------------------------------- | +| string | String type.| +| ArrayBuffer | Binary type.| + ## WebStorageOrigin Provides usage information of the Web SQL Database. @@ -4143,14 +4517,6 @@ Obtains the page record with the specified index in the history stack. | --------------------------- | ------------ | | [HistoryItem](#historyitem) | Historical page record.| -**Error codes** - -For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). - -| ID| Error Message | -| -------- | ----------------------- | -| 401 | Invalid input parameter | - **Example** ```ts @@ -4172,7 +4538,7 @@ struct WebComponent { let list = this.controller.getBackForwardEntries(); let historyItem = list.getItemAtIndex(list.currentIndex); console.log("HistoryItem: " + JSON.stringify(historyItem)); - this.icon = item.icon; + this.icon = historyItem.icon; } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -4196,4 +4562,14 @@ Describes a historical page record. | historyRawUrl | string | Yes | No | Original URL of the historical page. | | title | string | Yes | No | Title of the historical page. | -### +## WebCustomScheme + +Defines a custom URL scheme. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| -------------- | --------- | ---- | ---- | ---------------------------- | +| schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters and include only lowercase letters, digits, periods (.), plus signs (+), and hyphens (-). | +| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | +| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index 0e9b480a1326760e25e56bca698bd8e8581bbb68..e2afb3e5eaa55dfb4d4509db3c87ba55821cd748 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -467,13 +467,13 @@ Sets whether to enable geolocation access. By default, this feature is enabled. mediaPlayGestureAccess(access: boolean) -Sets whether a manual click is required for video playback. +Sets whether video playback must be started by user gestures. This API is not applicable to videos that do not have an audio track or whose audio track is muted. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ------ | ------- | ---- | ---- | ----------------- | -| access | boolean | Yes | true | Whether a manual click is required for video playback.| +| access | boolean | Yes | true | Whether video playback must be started by user gestures.| **Example** @@ -522,6 +522,109 @@ Sets whether to enable the multi-window permission. } ``` +### horizontalScrollBarAccess9+ + +horizontalScrollBarAccess(horizontalScrollBar: boolean) + +Sets whether to display the horizontal scrollbar, including the system default scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ----------- | ------- | ---- | ----- | ------------ | +| horizontalScrollBar | boolean | Yes | true | Whether to display the horizontal scrollbar.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .horizontalScrollBarAccess(true) + } + } + } + ``` + + ```html + + + + + Demo + + + + Scroll Test + + + ``` + +### verticalScrollBarAccess9+ + +verticalScrollBarAccess(verticalScrollBar: boolean) + +Sets whether to display the vertical scrollbar, including the system default scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ----------- | ------- | ---- | ----- | ------------ | +| verticalScrollBarAccess | boolean | Yes | true | Whether to display the vertical scrollbar.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .verticalScrollBarAccess(true) + } + } + } + ``` + + ```html + + + + + Demo + + + + Scroll Test + + + ``` + + ### cacheMode cacheMode(cacheMode: CacheMode) @@ -707,13 +810,13 @@ Sets whether to block online downloads. defaultFixedFontSize(size: number) -Sets the default fixed font size of the web page. +Sets the default fixed font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ---------------------------- | -| size | number | Yes | 13 | Default fixed font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 13 | Default fixed font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -724,11 +827,11 @@ Sets the default fixed font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 16 + @State fontSize: number = 16 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .defaultFixedFontSize(this.size) + .defaultFixedFontSize(this.fontSize) } } } @@ -738,13 +841,13 @@ Sets the default fixed font size of the web page. defaultFontSize(size: number) -Sets the default font size of the web page. +Sets the default font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ------------------------ | -| size | number | Yes | 16 | Default font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 16 | Default font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -755,11 +858,11 @@ Sets the default font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 13 + @State fontSize: number = 13 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .defaultFontSize(this.size) + .defaultFontSize(this.fontSize) } } } @@ -769,13 +872,44 @@ Sets the default font size of the web page. minFontSize(size: number) -Sets the minimum font size of the web page. +Sets the minimum font size for the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ------------------------ | +| size | number | Yes | 8 | Minimum font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State fontSize: number = 13 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .minFontSize(this.fontSize) + } + } + } + ``` + +### minLogicalFontSize9+ + +minLogicalFontSize(size: number) + +Sets the minimum logical font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ------------------------ | -| size | number | Yes | 8 | Minimum font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 8 | Minimum logical font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -786,27 +920,28 @@ Sets the minimum font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 13 + @State fontSize: number = 13 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .minFontSize(this.size) + .minLogicalFontSize(this.fontSize) } } } ``` + ### webFixedFont9+ webFixedFont(family: string) -Sets the fixed font family of the web page. +Sets the fixed font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | --------- | ---------------------------- | -| family | string | Yes | monospace | Fixed font family of the web page.| +| family | string | Yes | monospace | Fixed font family to set.| **Example** @@ -831,13 +966,13 @@ Sets the fixed font family of the web page. webSansSerifFont(family: string) -Sets the sans serif font family of the web page. +Sets the sans serif font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ---------- | --------------------------------- | -| family | string | Yes | sans-serif | Sans serif font family of the web page.| +| family | string | Yes | sans-serif | Sans serif font family to set.| **Example** @@ -862,13 +997,13 @@ Sets the sans serif font family of the web page. webSerifFont(family: string) -Sets the serif font family of the web page. +Sets the serif font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ---------------------------- | -| family | string | Yes | serif | Serif font family of the web page.| +| family | string | Yes | serif | Serif font family to set.| **Example** @@ -893,13 +1028,13 @@ Sets the serif font family of the web page. webStandardFont(family: string) -Sets the standard font family of the web page. +Sets the standard font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ---------- | ------------------------------- | -| family | string | Yes | sans serif | Standard font family of the web page.| +| family | string | Yes | sans serif | Standard font family to set.| **Example** @@ -924,13 +1059,13 @@ Sets the standard font family of the web page. webFantasyFont(family: string) -Sets the fantasy font family of the web page. +Sets the fantasy font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ------- | ------------------------------ | -| family | string | Yes | fantasy | Fantasy font family of the web page.| +| family | string | Yes | fantasy | Fantasy font family to set.| **Example** @@ -955,13 +1090,13 @@ Sets the fantasy font family of the web page. webCursiveFont(family: string) -Sets the cursive font family of the web page. +Sets the cursive font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ------- | ------------------------------ | -| family | string | Yes | cursive | Cursive font family of the web page.| +| family | string | Yes | cursive | Cursive font family to set.| **Example** @@ -982,6 +1117,100 @@ Sets the cursive font family of the web page. } ``` +### darkMode9+ + +darkMode(mode: WebDarkMode) + +Sets the web dark mode. By default, web dark mode is disabled. When it is enabled, the **\** component enables the dark theme defined for web pages if the theme has been defined in **prefer-color-scheme** of a media query, and remains unchanged otherwise. To enable the forcible dark mode, use this API with [forceDarkAccess](#forcedarkaccess9). + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | ----------- | ---- | --------------- | ------------------ | +| mode | [WebDarkMode](#webdarkmode9) | Yes | WebDarkMode.Off | Web dark mode to set.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State mode: WebDarkMode = WebDarkMode.On + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .darkMode(this.mode) + } + } + } + ``` + +### forceDarkAccess9+ + +forceDarkAccess(access: boolean) + +Sets whether to enable forcible dark mode for the web page. By default, this feature is turned off. This API is applicable only when dark mode is enabled in [darkMode](#darkmode9). + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | ------- | ---- | ----- | ------------------ | +| access | boolean | Yes | false | Whether to enable forcible dark mode for the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State mode: WebDarkMode = WebDarkMode.On + @State access: boolean = true + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .darkMode(this.mode) + .forceDarkAccess(this.access) + } + } + } + ``` + +### pinchSmooth9+ + +pinchSmooth(isEnabled: boolean) + +Sets whether to enable smooth pinch mode for the web page. + +**Parameters** + +| Name | Type| Mandatory| Default Value| Description | +| --------- | -------- | ---- | ------ | -------------------------- | +| isEnabled | boolean | Yes | false | Whether to enable smooth pinch mode for the web page.| + +**Example** + + ```ts +// xxx.ets +import web_webview from '@ohos.web.webview' +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .pinchSmooth(true) + } + } +} + ``` + ## Events The universal events are not supported. @@ -998,7 +1227,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1056,7 +1285,7 @@ Triggered when this page is about to exit after the user refreshes or closes the | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1117,7 +1346,7 @@ Triggered when **confirm()** is invoked by the web page. | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1177,7 +1406,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1361,7 +1590,7 @@ Triggered when an HTTP error (the response code is greater than or equal to 400) | Name | Type | Description | | ------- | ---------------------------------------- | --------------- | | request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. | -| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.| +| response | [WebResourceResponse](#webresourceresponse) | Encapsulation of a resource response.| **Example** @@ -1564,7 +1793,7 @@ Triggered when loading of the web page is complete. This API is used by an appli } ``` -### onRenderExited +### onRenderExited9+ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void) @@ -1831,7 +2060,7 @@ Invoked when an HTTP authentication request is received. | Name | Type | Description | | ------- | ------------------------------------ | ---------------- | -| handler | [HttpAuthHandler](#httpauthhandler9) | The user's operation. | +| handler | [HttpAuthHandler](#httpauthhandler9) | User operation. | | host | string | Host to which HTTP authentication credentials apply.| | realm | string | Realm to which HTTP authentication credentials apply. | @@ -1900,7 +2129,7 @@ Invoked when an SSL error occurs during resource loading. | Name | Type | Description | | ------- | ------------------------------------ | -------------- | -| handler | [SslErrorHandler](#sslerrorhandler9) | The user's operation.| +| handler | [SslErrorHandler](#sslerrorhandler9) | User operation.| | error | [SslError](#sslerror9) | Error code. | **Example** @@ -1945,7 +2174,7 @@ Invoked when an SSL error occurs during resource loading. ### onClientAuthenticationRequest9+ -onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\, issuers : Array\}) => void) +onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array, issuers : Array}) => void) Invoked when an SSL client certificate request is received. @@ -1953,11 +2182,11 @@ Invoked when an SSL client certificate request is received. | Name | Type | Description | | -------- | ---------------------------------------- | --------------- | -| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation. | +| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | User operation. | | host | string | Host name of the server that requests a certificate. | | port | number | Port number of the server that requests a certificate. | -| keyTypes | Array\ | Acceptable asymmetric private key types. | -| issuers | Array\ | Issuer of the certificate that matches the private key.| +| keyTypes | Array | Acceptable asymmetric private key types. | +| issuers | Array | Issuer of the certificate that matches the private key.| **Example** ```ts @@ -2008,7 +2237,7 @@ Invoked when a permission request is received. | Name | Type | Description | | ------- | ---------------------------------------- | -------------- | -| request | [PermissionRequest](#permissionrequest9) | The user's operation.| +| request | [PermissionRequest](#permissionrequest9) | User operation.| **Example** @@ -2051,7 +2280,7 @@ Invoked when a permission request is received. onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean) -Invoked when a context menu is displayed upon a long press on a specific element (such as an image or link). +Shows a context menu after the user clicks the right mouse button or long presses a specific element, such as an image or a link. **Parameters** @@ -2131,7 +2360,7 @@ Registers a callback for receiving a request to obtain the geolocation informati | Name | Type | Description | | ----------- | ------------------------------- | -------------- | | origin | string | Index of the origin. | -| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.| +| geolocation | [JsGeolocation](#jsgeolocation) | User operation.| **Example** @@ -2285,6 +2514,7 @@ Registers a callback for window creation. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { @@ -2626,7 +2856,7 @@ Notifies the **\** component of the user's confirm operation in the dialog ## FullScreenExitHandler9+ -Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see onFullScreenEnter. +Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9). ### exitFullScreen9+ @@ -2830,15 +3060,15 @@ Obtains the MIME type of the resource response. ### setResponseData9+ -setResponseData(data: string) +setResponseData(data: string | number) Sets the data in the resource response. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | ----------- | -| data | string | Yes | - | Resource response data to set.| +| Name| Type | Mandatory| Default Value| Description | +| ------ | ---------------- | ---- | ------ | ------------------------------------------------------------ | +| data | string \| number | Yes | - | Resource response data to set. When set to a number, the value indicates a file handle.| ### setResponseEncoding9+ @@ -2900,6 +3130,18 @@ Sets the status code of the resource response. | ---- | ------ | ---- | ---- | ------------- | | code | number | Yes | - | Status code to set.| +### setResponseIsReady9+ + +setResponseIsReady(IsReady: boolean) + +Sets whether the resource response data is ready. + +**Parameters** + +| Name | Type| Mandatory| Default Value| Description | +| ------- | -------- | ---- | ------ | -------------------------- | +| IsReady | boolean | Yes | true | Whether the resource response data is ready.| + ## FileSelectorResult9+ Notifies the **\** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9). @@ -3098,11 +3340,46 @@ Grants the permission for resources requested by the web page. | Name | Type | Mandatory | Default Value | Description | | --------- | --------------- | ---- | ---- | ------------- | -| resources | Array\ | Yes | - | List of accessible resources requested by the web page.| +| resources | Array\ | Yes | - | List of resources that can be requested by the web page with the permission to grant.| + +## ContextMenuSourceType9+ +| Name | Description | +| -------------------- | ---------- | +| None | Other event sources. | +| Mouse | Mouse event. | +| LongPress | Long press event. | + +## ContextMenuMediaType9+ + +| Name | Description | +| ------------ | ----------- | +| None | Non-special media or other media types.| +| Image | Image. | + +## ContextMenuInputFieldType9+ + +| Name | Description | +| ------------ | ----------- | +| None | Non-input field. | +| PlainText | Plain text field, such as the text, search, or email field. | +| Password | Password field. | +| Number | Numeric field. | +| Telephone | Phone number field.| +| Other | Field of any other type. | + +## ContextMenuEditStateFlags9+ + +| Name | Description | +| ------------ | ----------- | +| NONE | Editing is not allowed. | +| CAN_CUT | The cut operation is allowed. | +| CAN_COPY | The copy operation is allowed. | +| CAN_PASTE | The paste operation is allowed. | +| CAN_SELECT_ALL | The select all operation is allowed.| ## WebContextMenuParam9+ -Provides the information about the context menu that is displayed when a page element is long pressed. For the sample code, see [onContextMenuShow](#oncontextmenushow9). +Implements a context menu, which is displayed after the user clicks the right mouse button or long presses a specific element, such as an image or a link. For the sample code, see [onContextMenuShow](#oncontextmenushow9). ### x9+ @@ -3176,9 +3453,81 @@ Checks whether image content exists. | ------- | ------------------------- | | boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.| +### getMediaType9+ + +getMediaType(): ContextMenuMediaType + +Obtains the media type of this web page element. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuMediaType](#contextmenumediatype9) | Media type of the web page element.| + +### getSelectionText9+ + +getSelectionText(): string + +Obtains the selected text. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| string | Selected text for the context menu. If no text is selected, null is returned.| + +### getSourceType9+ + +getSourceType(): ContextMenuSourceType + +Obtains the event source of the context menu. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuSourceType](#contextmenusourcetype9) | Event source of the context menu.| + +### getInputFieldType9+ + +getInputFieldType(): ContextMenuInputFieldType + +Obtains the input field type of this web page element. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuInputFieldType](#contextmenuinputfieldtype9) | Input field type.| + +### isEditable9+ + +isEditable(): boolean + +Checks whether this web page element is editable. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| boolean | Returns **true** if the web page element is editable; returns **false** otherwise.| + +### getEditStateFlags9+ + +getEditStateFlags(): number + +Obtains the edit state flag of this web page element. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| number | Edit state flag of the web page element. For details, see [ContextMenuEditStateFlags](#contextmenueditstateflags9).| + ## WebContextMenuResult9+ -Implements a **WebContextMenuResult** object. For the sample code, see onContextMenuShow. +Implements a **WebContextMenuResult** object. For the sample code, see [onContextMenuShow](#oncontextmenushow9). ### closeContextMenu9+ @@ -3192,6 +3541,30 @@ copyImage(): void Copies the image specified in **WebContextMenuParam**. +### copy9+ + +copy(): void + +Performs the copy operation related to this context menu. + +### paste9+ + +paste(): void + +Performs the paste operation related to this context menu. + +### cut9+ + +cut(): void + +Performs the cut operation related to this context menu. + +### selectAll9+ + +selectAll(): void + +Performs the select all operation related to this context menu. + ## JsGeolocation Implements the **PermissionRequest** object. For the sample code, see [onGeolocationShow Event](#ongeolocationshow). @@ -3208,24 +3581,28 @@ Sets the geolocation permission status of a web page. | ------ | ------- | ---- | ---- | ---------------------------------------- | | origin | string | Yes | - | Index of the origin. | | allow | boolean | Yes | - | Geolocation permission status. | -| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.| +| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. You can manage the geolocation permissions saved to the system through [GeolocationPermissions9+](../apis/js-apis-webview.md#geolocationpermissions).| ## WebController Implements a **WebController** to control the behavior of the **\** component. A **WebController** can control only one **\** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\** component. +This API is deprecated since API version 9. You are advised to use [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller). + ### Creating an Object ``` webController: WebController = new WebController() ``` -### requestFocus +### requestFocus(deprecated) requestFocus() Requests focus for this web page. +This API is deprecated since API version 9. You are advised to use [requestFocus9+](../apis/js-apis-webview.md#requestfocus). + **Example** ```ts @@ -3247,12 +3624,14 @@ Requests focus for this web page. } ``` -### accessBackward +### accessBackward(deprecated) accessBackward(): boolean Checks whether going to the previous page can be performed on the current page. +This API is deprecated since API version 9. You are advised to use [accessBackward9+](../apis/js-apis-webview.md#accessbackward). + **Return value** | Type | Description | @@ -3281,12 +3660,14 @@ Checks whether going to the previous page can be performed on the current page. } ``` -### accessForward +### accessForward(deprecated) accessForward(): boolean Checks whether going to the next page can be performed on the current page. +This API is deprecated since API version 9. You are advised to use [accessForward9+](../apis/js-apis-webview.md#accessforward). + **Return value** | Type | Description | @@ -3315,12 +3696,14 @@ Checks whether going to the next page can be performed on the current page. } ``` -### accessStep +### accessStep(deprecated) accessStep(step: number): boolean Performs a specific number of steps forward or backward from the current page. +This API is deprecated since API version 9. You are advised to use [accessStep9+](../apis/js-apis-webview.md#accessstep). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3356,12 +3739,14 @@ Performs a specific number of steps forward or backward from the current page. } ``` -### backward +### backward(deprecated) backward(): void Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. +This API is deprecated since API version 9. You are advised to use [backward9+](../apis/js-apis-webview.md#backward). + **Example** ```ts @@ -3383,12 +3768,14 @@ Goes to the previous page based on the history stack. This API is generally used } ``` -### forward +### forward(deprecated) forward(): void Goes to the next page based on the history stack. This API is generally used together with **accessForward**. +This API is deprecated since API version 9. You are advised to use [forward9+](../apis/js-apis-webview.md#forward). + **Example** ```ts @@ -3444,12 +3831,14 @@ Performs a specific number of steps forward or backward on the current page base } ``` -### deleteJavaScriptRegister +### deleteJavaScriptRegister(deprecated) deleteJavaScriptRegister(name: string) Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refresh) API. +This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister9+](../apis/js-apis-webview.md#deletejavascriptregister). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3478,12 +3867,14 @@ Deletes a specific application JavaScript object that is registered with the win } ``` -### getHitTest +### getHitTest(deprecated) getHitTest(): HitTestType Obtains the element type of the area being clicked. +This API is deprecated since API version 9. You are advised to use [getHitTest9+](../apis/js-apis-webview.md#gethittest). + **Return value** | Type | Description | @@ -3678,7 +4069,7 @@ Obtains the default user agent of the current web page. } ``` -### loadData +### loadData(deprecated) loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }) @@ -3688,6 +4079,8 @@ If **baseUrl** is set to a data URL, the encoded string will be loaded by the ** If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **\** component as a non-encoded string in a manner similar to **loadUrl**. +This API is deprecated since API version 9. You are advised to use [loadData9+](../apis/js-apis-webview.md#loaddata). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3723,7 +4116,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces } ``` -### loadUrl +### loadUrl(deprecated) loadUrl(options: { url: string | Resource, headers?: Array\ }) @@ -3733,6 +4126,8 @@ The object injected through **loadUrl** is valid only in the current document. I The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**. +This API is deprecated since API version 9. You are advised to use [loadUrl9+](../apis/js-apis-webview.md#loadurl). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3761,12 +4156,14 @@ The object injected through **registerJavaScriptProxy** is still valid on a new } ``` -### onActive +### onActive(deprecated) onActive(): void Invoked when the **\** component enters the active state. +This API is deprecated since API version 9. You are advised to use [onActive9+](../apis/js-apis-webview.md#onactive). + **Example** ```ts @@ -3788,12 +4185,14 @@ Invoked when the **\** component enters the active state. } ``` -### onInactive +### onInactive(deprecated) onInactive(): void Invoked when the **\** component enters the inactive state. +This API is deprecated since API version 9. You are advised to use [onInactive9+](../apis/js-apis-webview.md#oninactive). + **Example** ```ts @@ -3815,11 +4214,13 @@ Invoked when the **\** component enters the inactive state. } ``` -### zoom +### zoom(deprecated) zoom(factor: number): void Sets a zoom factor for the current web page. +This API is deprecated since API version 9. You are advised to use [zoom9+](../apis/js-apis-webview.md#zoom). + **Parameters** | Name | Type | Mandatory | Description | @@ -3914,12 +4315,14 @@ Zooms out of this web page by 20%. } ``` -### refresh +### refresh(deprecated) refresh() Invoked when the **\** component refreshes the web page. +This API is deprecated since API version 9. You are advised to use [refresh9+](../apis/js-apis-webview.md#refresh). + **Example** ```ts @@ -3941,11 +4344,13 @@ Invoked when the **\** component refreshes the web page. } ``` -### registerJavaScriptProxy +### registerJavaScriptProxy(deprecated) registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\ }) -Registers a JavaScript object and invokes the methods of the object in the window. You must invoke the [refresh](#refresh) API for the registration to take effect. +Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. You must invoke the [refresh](#refresh) API for the registration to take effect. + +This API is deprecated since API version 9. You are advised to use [registerJavaScriptProxy9+](../apis/js-apis-webview.md#registerjavascriptproxy). **Parameters** @@ -4007,12 +4412,14 @@ Registers a JavaScript object and invokes the methods of the object in the windo ``` -### runJavaScript +### runJavaScript(deprecated) runJavaScript(options: { script: string, callback?: (result: string) => void }) Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. +This API is deprecated since API version 9. You are advised to use [runJavaScript9+](../apis/js-apis-webview.md#runjavascript). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -4066,12 +4473,14 @@ Executes a JavaScript script. This API uses an asynchronous callback to return t ``` -### stop +### stop(deprecated) stop() Stops page loading. +This API is deprecated since API version 9. You are advised to use [stop9+](../apis/js-apis-webview.md#stop). + **Example** ```ts @@ -4093,12 +4502,14 @@ Stops page loading. } ``` -### clearHistory +### clearHistory(deprecated) clearHistory(): void Clears the browsing history. +This API is deprecated since API version 9. You are advised to use [clearHistory9+](../apis/js-apis-webview.md#clearhistory). + **Example** ```ts @@ -4626,7 +5037,7 @@ Obtains the cookie value corresponding to the specified URL. Column() { Button('getCookie') .onClick(() => { - let value = webview.WebCookieManager.getCookie('www.example.com') + let value = web_webview.WebCookieManager.getCookie('www.example.com') console.log("value: " + value) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4676,44 +5087,10 @@ Sets a cookie value for the specified URL. } ``` -### saveCookieSync9+ -saveCookieSync(): boolean - -Saves the cookies in the memory to the drive. This API returns the result synchronously. - -**Return value** - -| Type | Description | -| ------- | -------------------- | -| boolean | Operation result.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('saveCookieSync') - .onClick(() => { - let result = web_webview.WebCookieManager.saveCookieSync() - console.log("result: " + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - ### saveCookieAsync9+ saveCookieAsync(): Promise\ -Saves cookies in the memory to the drive. This API uses a promise to return the value. +Saves the cookies in the memory to the drive. This API uses a promise to return the value. **Return value** @@ -4752,7 +5129,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the ### saveCookieAsync9+ saveCookieAsync(callback: AsyncCallback\): void -Saves cookies in the memory to the drive. This API uses an asynchronous callback to return the result. +Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. **Parameters** @@ -4998,158 +5375,7 @@ Deletes all session cookies. Column() { Button('deleteSessionCookie') .onClick(() => { - webview.WebCookieManager.deleteSessionCookie() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -## WebDataBase9+ -Implements the **WebDataBase** object. - -### existHttpAuthCredentials9+ - -static existHttpAuthCredentials(): boolean - -Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. - -**Return value** - -| Type | Description | -| ------- | ---------------------------------------- | -| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('existHttpAuthCredentials') - .onClick(() => { - let result = web_webview.WebDataBase.existHttpAuthCredentials() - console.log('result: ' + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### deleteHttpAuthCredentials9+ - -static deleteHttpAuthCredentials(): void - -Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('deleteHttpAuthCredentials') - .onClick(() => { - web_webview.WebDataBase.deleteHttpAuthCredentials() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getHttpAuthCredentials9+ - -static getHttpAuthCredentials(host: string, realm: string): Array\ - -Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ----- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host to which HTTP authentication credentials apply.| -| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | - -**Return value** - -| Type | Description | -| --------------- | ---------------------- | -| Array\ | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - host: string = "www.spincast.org" - realm: string = "protected example" - username_password: string[] - build() { - Column() { - Button('getHttpAuthCredentials') - .onClick(() => { - this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm) - console.log('num: ' + this.username_password.length) - ForEach(this.username_password, (item) => { - console.log('username_password: ' + item) - }, item => item) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### saveHttpAuthCredentials9+ - -static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void - -Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host to which HTTP authentication credentials apply.| -| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | -| username | string | Yes | - | User name. | -| password | string | Yes | - | Password. | - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - host: string = "www.spincast.org" - realm: string = "protected example" - build() { - Column() { - Button('saveHttpAuthCredentials') - .onClick(() => { - web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche") + web_webview.WebCookieManager.deleteSessionCookie() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5157,783 +5383,88 @@ Saves HTTP authentication credentials for a given host and realm. This API retur } ``` -## GeolocationPermissions9+ - -Implements a **GeolocationPermissions** object. - -### allowGeolocation9+ - -static allowGeolocation(origin: string): void - -Allows the specified origin to use the geolocation information. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| - -**Example** +## MessageLevel - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('allowGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.allowGeolocation(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Name | Description | +| ----- | :---- | +| Debug | Debug level.| +| Error | Error level.| +| Info | Information level.| +| Log | Log level.| +| Warn | Warning level. | -### deleteGeolocation9+ +## RenderExitReason -static deleteGeolocation(origin: string): void +Enumerates the reasons why the rendering process exits. -Clears the geolocation permission status of a specified origin. +| Name | Description | +| -------------------------- | ----------------- | +| ProcessAbnormalTermination | The rendering process exits abnormally. | +| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| +| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | +| ProcessOom | The program memory is running low. | +| ProcessExitUnknown | Other reason. | -**Parameters** +## MixedMode -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| +| Name | Description | +| ---------- | ---------------------------------- | +| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| +| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | +| None | HTTP and HTTPS hybrid content cannot be loaded. | -**Example** +## CacheMode +| Name | Description | +| ------- | ------------------------------------ | +| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| +| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | +| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | +| Only | The cache alone is used to load the resources. | - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('deleteGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.deleteGeolocation(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +## FileSelectorMode +| Name | Description | +| -------------------- | ---------- | +| FileOpenMode | Open and upload a file. | +| FileOpenMultipleMode | Open and upload multiple files. | +| FileOpenFolderMode | Open and upload a folder.| +| FileSaveMode | Save a file. | -### deleteAllGeolocation9+ + ## HitTestType -static deleteAllGeolocation(): void +| Name | Description | +| ------------- | ------------------------ | +| EditText | Editable area. | +| Email | Email address. | +| HttpAnchor | Hyperlink whose **src** is **http**. | +| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| +| Img | HTML::img tag. | +| Map | Geographical address. | +| Phone | Phone number. | +| Unknown | Unknown content. | -Clears the geolocation permission status of all sources. +## SslError9+ -**Example** +Enumerates the error codes returned by **onSslErrorEventReceive** API. - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('deleteAllGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.deleteAllGeolocation() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Name | Description | +| ------------ | ----------- | +| Invalid | Minor error. | +| HostMismatch | The host name does not match. | +| DateInvalid | The certificate has an invalid date. | +| Untrusted | The certificate issuer is not trusted.| -### getAccessibleGeolocation9+ +## ProtectedResourceType9+ -static getAccessibleGeolocation(origin: string, callback: AsyncCallback\): void +| Name | Description | Remarks | +| --------- | ------------- | -------------------------- | +| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| -Obtains the geolocation permission status of the specified source. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------------------------ | ---- | ---- | ---------------------------------------- | -| origin | string | Yes | - | Index of the origin. | -| callback | AsyncCallback\ | Yes | - | Callback used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('getAccessibleGeolocationAsync') - .onClick(() => { - web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { - if (error) { - console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)) - return - } - console.log('getAccessibleGeolocationAsync result: ' + result) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getAccessibleGeolocation9+ - -static getAccessibleGeolocation(origin: string): Promise\ - -Obtains the geolocation permission status of the specified source. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| - -**Return value** - -| Type | Description | -| ------------------ | ---------------------------------------- | -| Promise\ | Promise used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('getAccessibleGeolocationPromise') - .onClick(() => { - web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => { - console.log('getAccessibleGeolocationPromise result: ' + result) - }).catch(error => { - console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getStoredGeolocation9+ - -static getStoredGeolocation(callback: AsyncCallback\\>): void - -Obtains the geolocation permission status of all sources. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | -------------------------------- | ---- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('getStoredGeolocationAsync') - .onClick(() => { - web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { - if (error) { - console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)) - return - } - let origins_str: string = origins.join() - console.log('getStoredGeolocationAsync origins: ' + origins_str) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getStoredGeolocation9+ - -static getStoredGeolocation(): Promise\\> - -Obtains the geolocation permission status of all sources. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | -------------------------------- | ---- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.| - -**Return value** - -| Type | Description | -| -------------------------- | -------------------------------- | -| Promise\\> | Promise used to return the geolocation permission status of all sources.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('getStoredGeolocationPromise') - .onClick(() => { - web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => { - let origins_str: string = origins.join() - console.log('getStoredGeolocationPromise origins: ' + origins_str) - }).catch(error => { - console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -## WebStorage9+ -Implements the **WebStorage** object, which can be used to manage the Web SQL and the HTML5 Web Storage API. All **\** components in an application share one **WebStorage**. -### deleteAllData9+ -static deleteAllData(): void - -Deletes all data in the Web SQL Database. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('deleteAllData') - .onClick(() => { - web_webview.WebStorage.deleteAllData() - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### deleteOrigin9+ -static deleteOrigin(origin : string): void - -Deletes all data in the specified origin. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getHttpAuthCredentials') - .onClick(() => { - web_webview.WebStorage.deleteOrigin(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOrigins9+ -static getOrigins(callback: AsyncCallback\>) : void - -Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the information about the origins. For details, see **WebStorageOrigin**.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOrigins') - .onClick(() => { - web_webview.WebStorage.getOrigins((error, origins) => { - if (error) { - console.log('error: ' + error) - return - } - for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin) - console.log('usage: ' + origins[i].usage) - console.log('quota: ' + origins[i].quota) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOrigins9+ -static getOrigins() : Promise\> - -Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. - -**Return value** - -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise> | Promise used to return the information about the origins. For details, see **WebStorageOrigin**.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOrigins') - .onClick(() => { - web_webview.WebStorage.getOrigins() - .then(origins => { - for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin) - console.log('usage: ' + origins[i].usage) - console.log('quota: ' + origins[i].quota) - } - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginQuota9+ -static getOriginQuota(origin : string, callback : AsyncCallback\) : void - -Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | --------- | -| origin | string | Yes | Index of the origin.| -| callback | AsyncCallback\ | Yes | Callback used to return the storage quota of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { - if (error) { - console.log('error: ' + error) - return - } - console.log('quota: ' + quota) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginQuota9+ -static getOriginQuota(origin : string) : Promise\ - -Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Return value** - -| Type | Description | -| ---------------- | ----------------------- | -| Promise\ | Promise used to return the storage quota of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginQuota(this.origin) - .then(quota => { - console.log('quota: ' + quota) - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginUsage9+ -static getOriginUsage(origin : string, callback : AsyncCallback\) : void - -Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---------- | -| origin | string | Yes | Index of the origin.| -| callback | AsyncCallback\ | Yes | Callback used to return the storage usage of the origin. | - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginUsage') - .onClick(() => { - web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { - if (error) { - console.log('error: ' + error) - return - } - console.log('usage: ' + usage) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginUsage9+ -static getOriginUsage(origin : string) : Promise\ - -Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Return value** - -| Type | Description | -| ---------------- | ---------------------- | -| Promise\ | Promise used to return the storage usage of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginUsage(this.origin) - .then(usage => { - console.log('usage: ' + usage) - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -## WebStorageOrigin9+ - -Provides usage information about the Web SQL Database. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| -| usage | number | Yes | Storage usage of the origin. | -| quota | number | Yes | Storage quota of the origin. | - -## MessageLevel - -| Name | Description | -| ----- | :---- | -| Debug | Debug level.| -| Error | Error level.| -| Info | Information level.| -| Log | Log level.| -| Warn | Warning level. | - -## RenderExitReason - -Enumerates the reasons why the rendering process exits. - -| Name | Description | -| -------------------------- | ----------------- | -| ProcessAbnormalTermination | The rendering process exits abnormally. | -| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| -| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | -| ProcessOom | The program memory is running low. | -| ProcessExitUnknown | Other reason. | - -## MixedMode - -| Name | Description | -| ---------- | ---------------------------------- | -| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| -| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | -| None | HTTP and HTTPS hybrid content cannot be loaded. | - -## CacheMode +## WebDarkMode9+ | Name | Description | | ------- | ------------------------------------ | -| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| -| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | -| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | -| Only | The cache alone is used to load the resources. | - -## FileSelectorMode -| Name | Description | -| -------------------- | ---------- | -| FileOpenMode | Open and upload a file. | -| FileOpenMultipleMode | Open and upload multiple files. | -| FileOpenFolderMode | Open and upload a folder.| -| FileSaveMode | Save a file. | - - ## HitTestType - -| Name | Description | -| ------------- | ------------------------ | -| EditText | Editable area. | -| Email | Email address. | -| HttpAnchor | Hyperlink whose **src** is **http**. | -| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| -| Img | HTML::img tag. | -| Map | Geographical address. | -| Phone | Phone number. | -| Unknown | Unknown content. | - -## SslError9+ - -Enumerates the error codes returned by **onSslErrorEventReceive** API. - -| Name | Description | -| ------------ | ----------- | -| Invalid | Minor error. | -| HostMismatch | The host name does not match. | -| DateInvalid | The certificate has an invalid date. | -| Untrusted | The certificate issuer is not trusted.| - -## ProtectedResourceType9+ - -| Name | Description | Remarks | -| --------- | ------------- | -------------------------- | -| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| - -## WebAsyncController - -Implements the **WebAsyncController** object, which can be used to control the behavior of a **\** component with asynchronous callbacks. A **WebAsyncController **object controls one **\** component. - -### Creating an Object - -``` -webController: WebController = new WebController(); -webAsyncController: WebAsyncController = new WebAsyncController(webController); -``` - -### storeWebArchive9+ - -storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback): void - -Stores this web page. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. -| callback | AsyncCallback | Yes | Callback used to return the save path if the operation is successful and null otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('saveWebArchive') - .onClick(() => { - let webAsyncController = new web_webview.WebAsyncController(this.controller) - webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { - if (filename != null) { - console.info(`save web archive success: ${filename}`) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### storeWebArchive9+ - -storeWebArchive(baseName: string, autoName: boolean): Promise - -Stores this web page. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. - -**Return value** - -| Type | Description | -| --------------- | -------------------------------- | -| Promise | Promise used to return the save path if the operation is successful and null otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - build() { - Column() { - Button('saveWebArchive') - .onClick(() => { - let webAsyncController = new web_webview.WebAsyncController(this.controller); - webAsyncController.storeWebArchive("/data/storage/el2/base/", true) - .then(filename => { - if (filename != null) { - console.info(`save web archive success: ${filename}`) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Off | The web dark mode is disabled. | +| On | The web dark mode is enabled. | +| Auto | The web dark mode setting follows the system settings. | ## WebMessagePort9+ @@ -6158,7 +5689,7 @@ Sets the message port in this object. For the complete sample code, see [postMes ## DataResubmissionHandler9+ -Implements the **DataResubmissionHandler** for resubmitting or canceling the web form data. +Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. ### resend9+ diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 8425cf29444183671c4fd8e3389bd0ffa28840f9..a603c54bc5f16e877420e80c1714ac16f70e2123 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -17,7 +17,7 @@ The location attributes set the alignment mode, layout direction, and position o | position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| | markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
} | | offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
} | -| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| +| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container. This attribute is valid only when the container is [\](ts-container-relativecontainer.md).
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| ## Example diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index b286cbf232d6d334444b164117fa289b79f9a6c4..28669ef9f2e4955e785462d935468bd519fd2931 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -33,8 +33,11 @@ - Security - [Ability Access Control Error Codes](errorcode-access-token.md) - [HUKS Error Codes](errorcode-huks.md) + - [User Authentication Error Codes](errorcode-useriam.md) - Data Management - [RDB Error Codes](errorcode-data-rdb.md) + - [DataShare Error Codes](errorcode-datashare.md) + - [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md) - [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) - [Preferences Error Codes](errorcode-preferences.md) - File Management diff --git a/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md new file mode 100644 index 0000000000000000000000000000000000000000..0ebad934ac37ea27b349fa9e2b0c0d4941f83ca3 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md @@ -0,0 +1,19 @@ +# Distributed Data Object Error Codes + +## 15400001 Failed to Create the In-Memory Database + +**Error Message** + +Create table failed. + +**Description** + +The in-memory database fails to be created. + +**Possible Causes** + +An object with the same session ID already exists. + +**Solution** + +Check for the object has been added to the same session. diff --git a/en/application-dev/reference/errorcodes/errorcode-useriam.md b/en/application-dev/reference/errorcodes/errorcode-useriam.md new file mode 100644 index 0000000000000000000000000000000000000000..2e84641a549af91c9101e94da86b54cf0db9d712 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-useriam.md @@ -0,0 +1,163 @@ +# User Authentication Error Codes + +## 201 Permission Verification Failed + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 202 Invoker Is Not a System Application + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 401 Parameter Check Failed. + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 12500001 Authentication Failed + +**Error Message** + +Authentication failed. + +**Possible Causes** + +The credential does not match the credential enrolled. + +**Solution** + +Initiate authentication again. + +## 12500002 General Operation Error + +**Error Message** + +General operation error. + +**Possible Causes** + +1. An error occurs when the NAPI layer parses parameters. +2. The process of the user authentication service is not started. +3. The proxy client fails to write data over IPC. +4. The stub server fails to parse data over IPC. +5. The driver service is not obtained. + +**Solution** + +Call the API again later or restart the device. + +## 12500003 Authentication Canceled + +**Error Message** + +Authentication canceled. + +**Possible Causes** + +The authentication operation has been canceled. + +**Solution** + +Initiate the authentication again. + +## 12500004 Authentication Timed Out + +**Error Message** + +Authentication timeout. + +**Possible Causes** + +The authentication is not complete within the specified time. + +**Solution** + +Initiate the authentication again. + +## 12500005 Unsupported Authentication Type + +**Error Message** + +The authentication type is not supported. + +**Possible Causes** + +1. The input authentication type parameter is not supported. For example, if the authentication type passed in **getAvailableStatus** of the **userAuth** module is not **FACE** or **FINGERPRINT**, error code 12500005 is returned. +2. The device does not support the authentication type. For example, if fingerprint authentication is initiated on a device that has no fingerprint sensor, error code 12500005 is returned. + +**Solution** + +Check the authentication type parameter and call the API again. + +## 12500006 Unsupported Authentication Trust Level + +**Error Message** + +The authentication trust level is not supported. + +**Possible Causes** + +1. The **authTrustLevel** value in **getAvailableStatus** or **getAuthInstance** of the **userAuth** module is not in the range [ATL1, ATL2, ATL3, ATL4]. +2. The device does not support the authentication trust level. For example, if facial authentication for payment is initiated on a device that has only 2D cameras, error code 12500006 is returned. + +**Solution** + +Check that the **authTrustLevel** passed in is within the value range, and the device supports the specified authentication trust level. + +## 12500007 Authentication Service Unavailable + +**Error Message** + +Authentication service is busy. + +**Possible Causes** + +Another authentication is initiated when the current authentication has not been finished yet. + +**Solution** + +Initiate authentication again later. + +## 12500009 Authentication Locked + +**Error Message** + +Authentication is lockout. + +**Possible Causes** + +The number of authentication failures exceeds the limit. + +**Solution** + +Initiate authentication later. + +## 12500010 Credential Not Enrolled + +**Error Message** + +The type of credential has not been enrolled. + +**Possible Causes** + +The **authType** parameter set in **getAvailableStatus** of the **userAuth** module is **FACE**, but no facial credential is enrolled in the device. +**start()** is called to initiate facial authentication, but no facial credential is enrolled in the device. + +**Solution** + +Check that the related type of credential has been enrolled in the device. + +## 12700001 Failed to Enroll Faces + +**Error Message** + +The operation is failed. + +**Possible Causes** + +1. The facial authentication service is not started when **setSurfaceId()** of the **userAuth** module is called. +2. The proxy client fails to write data over IPC. +3. The stub server fails to parse data over IPC. +4. An error occurs when the facial authentication driver is invoked. + +**Solution** + +Call the API again later or restart the device. diff --git a/en/application-dev/security/cryptoFramework-guidelines.md b/en/application-dev/security/cryptoFramework-guidelines.md index 35784280547f6f5064fc13f15d651801ea0d0b02..1d61382eb57babf5a33a0768a2e0248307b223d5 100644 --- a/en/application-dev/security/cryptoFramework-guidelines.md +++ b/en/application-dev/security/cryptoFramework-guidelines.md @@ -32,8 +32,8 @@ The table below describes the APIs used in this guide. |AsyKeyGenerator|generateKeyPair() : Promise\|Generates an asymmetric key pair randomly. This API uses a promise to return the result.| |SymKeyGenerator|generateSymKey(callback : AsyncCallback\) : void|Generates a symmetric key randomly. This API uses an asynchronous callback to return the result.| |SymKeyGenerator|generateSymKey() : Promise\|Generates a symmetric key randomly. This API uses a promise to return the result.| -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) | -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary public key and private key data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) | +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.)| +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.)| | SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts binary data into a symmetric key. This API uses an asynchronous callback to return the result.| | SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts binary data into a symmetric key. This API uses a promise to return the result.| | Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)| @@ -264,14 +264,14 @@ function stringToUint8Array(str) { return new Uint8Array(arr); } -// Convert byte streams into strings in plaintext. +// Output the byte streams in hexadecimal format. function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -// Output the byte streams in hexadecimal format. +// Convert byte streams into strings in plaintext. function uint8ArrayToString(array) { let arrayString = ''; for (let i = 0; i < array.length; i++) { @@ -383,14 +383,14 @@ function stringToUint8Array(str) { return new Uint8Array(arr); } -// Convert byte streams into strings in plaintext. +// Output the byte streams in hexadecimal format. function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -// Output the byte streams in hexadecimal format. +// Convert byte streams into strings in plaintext. function uint8ArrayToString(array) { let arrayString = ''; for (let i = 0; i < array.length; i++) { @@ -500,7 +500,7 @@ Example 2: Encrypt and decrypt data using an asymmetric key pair. Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. -3. Perform encryption and decryption operations. +3. Perform encryption and decryption operations. Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. @@ -573,38 +573,24 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry |Sign|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Sign** instance. This API uses a promise to return the result.| |Sign|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signing. This API uses an asynchronous callback to return the result.| |Sign|update(data : DataBlob) : Promise\|Updates the data for signing. This API uses a promise to return the result.| -|Sign|sign(data : DataBlob, callback : AsyncCallback) : void|Signs the data. This API uses an asynchronous callback to return the result.| -|Sign|sign(data : DataBlob) : Promise|Signs the data. This API uses a promise to return the result.| +|Sign|sign(data : DataBlob, callback : AsyncCallback\) : void|Signs the data. This API uses an asynchronous callback to return the result.| +|Sign|sign(data : DataBlob) : Promise\|Signs the data. This API uses a promise to return the result.| |cryptoFramework|function createVerify(algName : string) : Verify|Creates a **Verify** instance.| |Verify|init(priKey : PriKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.| |Verify|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.| |Verify|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signature verification. This API uses an asynchronous callback to return the result.| |Verify|update(data : DataBlob) : Promise\|Updates the data for signature verification. This API uses a promise to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise|Verifies the signature. This API uses a promise to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies the signature. This API uses a promise to return the result.| **How to Develop** Example 1: Use RSA to sign data and verify the signature. -1. Generate an RSA key pair. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. - -2. Create a **Sign** instance. - - Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. - -3. Generate a signature. - - Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. - -4. Create a **Verify** instance. - - Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. - -5. Verify the signature. - - Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -684,25 +670,11 @@ function verifyMessageCallback() { ``` Example 2: Using ECC to sign data and verify the signature. -1. Generate an ECC key. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. - -2. Create a **Sign** instance. - - Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. - -3. Generate a signature. - - Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. - -4. Create a **Verify** instance. - - Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. - -5. Verify the signature. - - Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -792,7 +764,7 @@ Typical message digest operations involve the following: 1. Create an **Md** instance. 2. Add one or more segments of data for generating a digest. -3. Compute a digest. +3. Compute a digest. 4. Obtain the algorithm and length of a digest. **Available APIs** @@ -802,10 +774,10 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------------- | | cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance. | -| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| -| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | -| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | -| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. | +| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| +| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | +| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | +| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. | | Md | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. | | Md | readonly algName : string; | Obtains the digest algorithm. | @@ -907,10 +879,7 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry **How to Develop** -1. Generate an ECC key. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. - +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. 2. Generate a shared secret by using the private and public ECC keys. ```javascript @@ -966,15 +935,15 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | --------------------------------------------------- | -| cryptoFramework | function createMac(algName : string) : Md; | Creates a **Mac** instance. | -| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| -| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | -| Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | -| Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | -| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | -| Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | +| cryptoFramework | function createMac(algName : string) : Mac; | Creates a **Mac** instance. | +| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| +| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | +| Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | +| Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | +| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | +| Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | | Mac | getMacLength() : number; | Obtains the length of the MAC based on the specified algorithm. | -| Mac | readonly algName : string; | Obtains the algorithm. | +| Mac | readonly algName : string; | Obtains the digest algorithm. | **How to Develop** @@ -1089,8 +1058,8 @@ function doHmacByCallback(algName) { Typical random number operations involve the following: -1. Generate a random number. -2. Set a seed based on the random number generated. +- Generate a random number. +- Set a seed based on the random number generated. **Available APIs** @@ -1099,10 +1068,9 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | ---------------------------------------------- | | cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. | -| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | -| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | -| Random | setSeed(seed : DataBlob, callback : AsyncCallback\) : void; | Sets a seed. This API uses an asynchronous callback to return the result.| -| Random | setSeed(seed : DataBlob) : Promise\; | Sets a seed. This API uses a promise to return the result. | +| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | +| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | +| Random | setSeed(seed : DataBlob) : void; | Sets a seed. | **How to Develop** @@ -1124,10 +1092,11 @@ function doRandByPromise(len) { var promiseGenerateRand = rand.generateRandom(len); promiseGenerateRand.then(randData => { console.error("[Promise]: rand result: " + randData.data); - var promiseSetSeed = rand.setSeed(randData); - return promiseSetSeed; - }).then(() => { - console.error("[Promise]: setSeed success"); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -1146,13 +1115,11 @@ function doRandByCallback(len) { console.error("[Callback]: err: " + err.code); } else { console.error("[Callback]: generate random result: " + randData.data); - rand.setSeed(randData, (err1,) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: setSeed success"); - } - }); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } } }); } diff --git a/en/application-dev/security/cryptoFramework-overview.md b/en/application-dev/security/cryptoFramework-overview.md index afaa9658f3b9bd55754f3d830090ff3eece4e26a..4037a163e5877320e551d202e68ff4f9dee658c3 100644 --- a/en/application-dev/security/cryptoFramework-overview.md +++ b/en/application-dev/security/cryptoFramework-overview.md @@ -1,5 +1,5 @@ # Crypto Framework Overview -The crypto framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hash, and secure random number. You can use the APIs provided by this framework to implement cipher development quickly. +The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hash, and secure random number. You can use the APIs provided by this framework to implement cipher development quickly. ## Working Principles The crypto framework provides components in the following layers: diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index 7f84d9cd058732ee490428034d90338bfaf7ea9c..073b31fc651ced76f80b95ed796ca452ca4c62d2 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -1,165 +1,1605 @@ -# App Permission List - -Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine whether the app can apply for the target permissions based on the table below. - -For details about permission usage examples, see [Permission Application Guide](accesstoken-guidelines.md). - -| Permission | APL | Authorization Mode | Enable ACL| Description | -| -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------- | -| ohos.permission.USE_BLUETOOTH | normal | system_grant | TRUE | Allows an app to access to Bluetooth configuration. | -| ohos.permission.DISCOVER_BLUETOOTH | normal | system_grant | TRUE | Allows an app to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. | -| ohos.permission.MANAGE_BLUETOOTH | system_basic | system_grant | TRUE | Allows an app to pair with a Bluetooth device and access the contacts or messages of the device. | -| ohos.permission.INTERNET | normal | system_grant | TRUE | Allows an app to access the Internet. | -| ohos.permission.
MODIFY_AUDIO_SETTINGS | normal | system_grant | TRUE | Allows an app to modify audio settings. | -| ohos.permission.
ACCESS_NOTIFICATION_POLICY | normal | system_grant | FALSE | Allows an app to access the notification policy on the device. | -| ohos.permission.GET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to read telephony information. | -| ohos.permission.REQUIRE_FORM | system_basic | system_grant | TRUE | Allows an app to obtain the Ability Form. | -| ohos.permission.GET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to obtain network information. | -| ohos.permission.PLACE_CALL | system_basic | system_grant | TRUE | Allows an app to make calls without starting the dialer. | -| ohos.permission.SET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to set data network information. | -| ohos.permission.REMOVE_CACHE_FILES | system_basic | system_grant | TRUE | Allows the cache of the specified app to be cleared. | -| ohos.permission.REBOOT | system_basic | system_grant | TRUE | Allows an app to restart the device. | -| ohos.permission.RUNNING_LOCK | normal | system_grant | TRUE | Allows an app to obtain a running lock. | -| ohos.permission.SET_TIME | system_basic | system_grant | TRUE | Allows an app to set the system time. | -| ohos.permission.SET_TIME_ZONE | system_basic | system_grant | TRUE | Allows an app to set the system time zone. | -| ohos.permission.
DOWNLOAD_SESSION_MANAGER | system_core | system_grant | TRUE | Allows an app to manage the download sessions. | -| ohos.permission.COMMONEVENT_STICKY | normal | system_grant | TRUE | Allows an app to publish sticky common events. | -| ohos.permission.SYSTEM_FLOAT_WINDOW | system_basic | system_grant | TRUE | Allows an app to be displayed in a floating window on top of other apps. | -| ohos.permission.PRIVACY_WINDOW | system_basic | system_grant | TRUE | Allows an app to set screens that cannot be captured or recorded. | -| ohos.permission.POWER_MANAGER | system_core | system_grant | TRUE | Allows an app to hibernate or wake up the device by calling APIs. | -| ohos.permission.REFRESH_USER_ACTION | system_basic | system_grant | TRUE | Allows an app to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen. | -| ohos.permission.POWER_OPTIMIZATION | system_basic | system_grant | TRUE | Allows an app to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes.| -| ohos.permission.REBOOT_RECOVERY | system_basic | system_grant | TRUE | Allows an app to restart the device and enter Recovery mode. | -| ohos.permission.
MANAGE_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows an app to manage local user accounts. | -| ohos.permission.
INTERACT_ACROSS_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows access between multiple OS accounts. | -| ohos.permission.VIBRATE | normal | system_grant | TRUE | Allows an app to control vibration. | -| ohos.permission.CONNECT_IME_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind to the **InputMethodAbility**. | -| ohos.permission.
CONNECT_SCREEN_SAVER_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind to the **ScreenSaverAbility**. | -| ohos.permission.
READ_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to read the screen saver information, such as the list of screen savers that have been installed and the activated one. | -| ohos.permission.
WRITE_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to modify the screen saver information, such as activating and previewing a screen saver. | -| ohos.permission.SET_WALLPAPER | normal | system_grant | TRUE | Allows an app to set a static wallpaper. | -| ohos.permission.GET_WALLPAPER | system_basic | system_grant | TRUE | Allows an app to read wallpaper files. | -| ohos.permission.
CHANGE_ABILITY_ENABLED_STATE | system_basic | system_grant | TRUE | Allows an app to enable or disable an app or component. | -| ohos.permission.ACCESS_MISSIONS | system_basic | system_grant | TRUE | Allows an app to obtain information about running processes and mission in a mission stack. | -| ohos.permission.
CLEAN_BACKGROUND_PROCESSES | normal | system_grant | TRUE | Allows an app to clear background processes based on their bundle names. | -| ohos.permission.
KEEP_BACKGROUND_RUNNING | normal | system_grant | TRUE | Allows a Service ability to keep running in the background. | -| ohos.permission.
UPDATE_CONFIGURATION | system_basic | system_grant | TRUE | Allows an app to modify system settings. | -| ohos.permission.UPDATE_SYSTEM | system_basic | system_grant | TRUE | Allows an app to call the update APIs. | -| ohos.permission.FACTORY_RESET | system_basic | system_grant | TRUE | Allows an app to call the APIs for restoring factory settings. | -| ohos.permission.
GRANT_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to grant sensitive permissions to other apps. | -| ohos.permission.
REVOKE_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to revoke sensitive permissions granted to other apps. | -| ohos.permission.
GET_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to obtain the sensitive permissions that have been granted to other apps. | -| ohos.permission.INTERACT_
ACROSS_LOCAL_ACCOUNTS_EXTENSION | system_core | system_grant | TRUE | Allows an app to set the attributes of apps of other users. | -| ohos.permission.LISTEN_BUNDLE_CHANGE | system_basic | system_grant | TRUE | Allows an app to listen for changes in other apps, when they are installed, updated, or uninstalled. | -| ohos.permission.GET_BUNDLE_INFO | normal | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | -| ohos.permission.ACCELEROMETER | normal | system_grant | TRUE | Allows an app to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. | -| ohos.permission.GYROSCOPE | normal | system_grant | TRUE | Allows an app to read data from a gyroscope sensor or uncalibrated gyroscope sensor. | -| ohos.permission.
GET_BUNDLE_INFO_PRIVILEGED | system_basic | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | -| ohos.permission.INSTALL_BUNDLE | system_core | system_grant | TRUE | Allows an app to install and uninstall other apps. | -| ohos.permission.MANAGE_SHORTCUTS | system_core | system_grant | TRUE | Allows an app to query and start shortcuts of other apps.| -| ohos.permission.radio.ACCESS_FM_AM | system_core | system_grant | TRUE | Allows an app to access radio services. | -| ohos.permission.SET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to change the telephone state. | -| ohos.permission.
START_ABILITIES_FROM_BACKGROUND | system_basic | system_grant | TRUE | Allows an app to start Feature abilities in the background. | -| ohos.permission.BUNDLE_ACTIVE_INFO | system_basic | system_grant | TRUE | Allows an app to obtain how long other apps have been running in the foreground or background. | -| ohos.permission.
START_INVISIBLE_ABILITY | system_core | system_grant | TRUE | Allows an app to start an invisible ability. | -| ohos.permission.sec.ACCESS_UDID | system_basic | system_grant | TRUE | Allows an app to obtain the Unified Device ID (UDID). | -| ohos.permission.
LAUNCH_DATA_PRIVACY_CENTER | system_basic | system_grant | TRUE | Allows an app to switch from its privacy statement page to the Data & privacy page. | -| ohos.permission.MANAGE_MEDIA_RESOURCES | system_basic | system_grant | TRUE | Allows an app to obtain and manage the media resources that are being played on the device.| -| ohos.permission.PUBLISH_AGENT_REMINDER | normal | system_grant | TRUE | Allows an app to use agent-powered reminders. | -| ohos.permission.
CONTROL_TASK_SYNC_ANIMATOR | system_core | system_grant | TRUE | Allows apps to use sync task animations. | -| ohos.permission.INPUT_MONITORING | system_core | system_grant | TRUE | Allows an app to listen for input events. Only the system signature apps can apply for this permission. | -| ohos.permission.MANAGE_MISSIONS | system_core | system_grant | TRUE | Allows an app to manage ability mission stacks. | -| ohos.permission.
NOTIFICATION_CONTROLLER | system_core | system_grant | TRUE | Allows an app to manage and subscribe to notifications. | -| ohos.permission.CONNECTIVITY_INTERNAL | system_basic | system_grant | TRUE | Allows an app to obtain network information or modify network settings. | -| ohos.permission.SET_ABILITY_CONTROLLER | system_basic | system_grant | TRUE | Allows an app to set the start and stop of an ability. | -| ohos.permission.USE_USER_IDM | system_basic | system_grant | FALSE | Allows an app to access the system identity credential information. | -| ohos.permission.MANAGE_USER_IDM | system_basic | system_grant | FALSE | Allows an app to use the system identity credential management capability to enroll, modify, and delete PINs, face images, and fingerprints.| -| ohos.permission.ACCESS_BIOMETRIC | normal | system_grant | TRUE | Allows an app to use biometric recognition for identity authentication. | -| ohos.permission.
ACCESS_USER_AUTH_INTERNAL | system_basic | system_grant | FALSE | Allows an app to use the system identity authentication capability to authenticate or identify users. | -| ohos.permission.ACCESS_PIN_AUTH | system_basic | system_grant | FALSE | Allows a system app to call the PIN input APIs to present a password input dialog box for users.| -| ohos.permission.GET_RUNNING_INFO | system_basic | system_grant | TRUE | Allows an app to obtain running status information. | -| ohos.permission.CLEAN_APPLICATION_DATA | system_basic | system_grant | TRUE | Allows an app to clear app data. | -| ohos.permission.RUNNING_STATE_OBSERVER | system_basic | system_grant | TRUE | Allows an app to observe the app status. | -| ohos.permission.CAPTURE_SCREEN | system_core | system_grant | TRUE | Allows an app to take screenshots. | -| ohos.permission.GET_WIFI_INFO | normal | system_grant | TRUE | Allows an app to obtain WLAN information. | -| ohos.permission.GET_WIFI_INFO_INTERNAL | system_core | system_grant | TRUE | Allows an app to obtain WLAN information. | -| ohos.permission.SET_WIFI_INFO | normal | system_grant | TRUE | Allows an app to set WLAN devices. | -| ohos.permission.GET_WIFI_PEERS_MAC | system_core | system_grant | TRUE | Allows an app to obtain the MAC address of the peer WLAN or Bluetooth device. | -| ohos.permission.GET_WIFI_LOCAL_MAC | system_basic | system_grant | TRUE | Allows an app to obtain the MAC address of the local WLAN or Bluetooth device. | -| ohos.permission.GET_WIFI_CONFIG | system_basic | system_grant | TRUE | Allows an app to obtain the WLAN configuration. | -| ohos.permission.SET_WIFI_CONFIG | system_basic | system_grant | TRUE | Allows an app to set WLAN information. | -| ohos.permission.
MANAGE_WIFI_CONNECTION | system_core | system_grant | TRUE | Allows an app to manage WLAN connections. | -| ohos.permission.MANAGE_WIFI_HOTSPOT | system_core | system_grant | TRUE | Allows an app to enable or disable Wi-Fi hotspots. | -| ohos.permission.GET_ALL_APP_ACCOUNTS | system_core | system_grant | FALSE | Allows an app to obtain all app account information. | -| ohos.permission.MANAGE_SECURE_SETTINGS | system_basic | system_grant | TRUE | Allows an app to modify security settings. | -| ohos.permission.READ_DFX_SYSEVENT | system_basic | system_grant | FALSE | Allows an app to obtain all app account information. | -| ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN | system_core | system_grant | TRUE | Allows an app to activate the device administrator app. | -| ohos.permission.SET_ENTERPRISE_INFO | system_basic | system_grant | TRUE | Allows the device administrator app to set enterprise information. | -| ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT | system_basic | system_grant | TRUE | Allows the device administrator app to subscribe to management events. | -| ohos.permission.ENTERPRISE_SET_DATETIME | system_basic | system_grant | TRUE | Allows the device administrator app to set the system time. | -| ohos.permission.ENTERPRISE_GET_DEVICE_INFO | system_basic | system_grant | TRUE | Allows the device administrator app to obtain device information. | -| ohos.permission.NFC_TAG | normal | system_grant | FALSE | Allows an app to read NFC tag information. | -| ohos.permission.NFC_CARD_EMULATION | normal | system_grant | FALSE | Allows an app to implement card emulation. | -| ohos.permission.PERMISSION_USED_STATS | system_basic | system_grant | TRUE | Allows a system application to access the permission usage records. | -| ohos.permission.
NOTIFICATION_AGENT_CONTROLLER | system_core | system_grant | TRUE | Allows an app to send agent-powered notifications. | -| ohos.permission.ANSWER_CALL | system_basic | user_grant | TRUE | Allows an app to answer incoming calls. | -| ohos.permission.READ_CALENDAR | normal | user_grant | TRUE | Allows an app to read calendar data. | -| ohos.permission.READ_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to read call logs. | -| ohos.permission.READ_CELL_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read cell broadcast messages received by the device. | -| ohos.permission.READ_CONTACTS | system_basic | user_grant | TRUE | Allows an app to read contacts. | -| ohos.permission.READ_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read messages. | -| ohos.permission.RECEIVE_MMS | system_basic | user_grant | TRUE | Allows an app to receive and process MMS messages. | -| ohos.permission.RECEIVE_SMS | system_basic | user_grant | TRUE | Allows an app to receive and process SMS messages. | -| ohos.permission.RECEIVE_WAP_MESSAGES | system_basic | user_grant | TRUE | Allows an app to receive and process WAP messages. | -| ohos.permission.MICROPHONE | normal | user_grant | TRUE | Allows an app to access the microphone. | -| ohos.permission.SEND_MESSAGES | system_basic | user_grant | TRUE | Allows an app to send messages. | -| ohos.permission.WRITE_CALENDAR | normal | user_grant | TRUE | Allows an app to add, remove, and modify calendar events. | -| ohos.permission.WRITE_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify call logs. | -| ohos.permission.WRITE_CONTACTS | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify contacts. | -| ohos.permission.DISTRIBUTED_DATASYNC | normal | user_grant | TRUE | Allows an app to exchange data with other devices. | -| ohos.permission.MANAGE_VOICEMAIL | system_basic | user_grant | TRUE | Allows an app to leave messages in the voice mailbox. | -| ohos.permission.
LOCATION_IN_BACKGROUND | normal | user_grant | FALSE | Allows an app running in the background to obtain the device location. | -| ohos.permission.LOCATION | normal | user_grant | TRUE | Allows an app to obtain the device location. | -| ohos.permission.APPROXIMATELY_LOCATION | normal | user_grant | FALSE | Allows an app to obtain the approximate location information of a device. | -| ohos.permission.MEDIA_LOCATION | normal | user_grant | TRUE | Allows an app to access geographical locations in the user's media file. | -| ohos.permission.CAMERA | normal | user_grant | TRUE | Allows an app to use the camera to take photos and record videos. | -| ohos.permission.READ_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from the user's external storage. | -| ohos.permission.WRITE_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from and write media files into the user's external storage. | -| ohos.permission.ACTIVITY_MOTION | normal | user_grant | TRUE | Allows an app to read the current workout status of the user. | -| ohos.permission.READ_HEALTH_DATA | normal | user_grant | TRUE | Allows an app to read the health data of the user. | -| ohos.permission.GET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | Allows an app to query default apps. | -| ohos.permission.SET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | Allows an app to set and reset default apps. | -| ohos.permission.
MANAGE_DISPOSED_APP_STATUS | system_core | system_grant | TRUE | Allows an app to set and query the app handling state. | -| ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | Allows an app to query the unique identifier of a device. | -| ohos.permission.DUMP | system_core | system_grant | TRUE | Allows the basic system information and SA service information to be exported. | -| ohos.permission.
DISTRIBUTED_SOFTBUS_CENTER | system_basic | system_grant | FALSE | Allows networking between different devices. | -| ohos.permission.ACCESS_DLP_FILE | system_core | system_grant | TRUE | Allows configuration and management of the permissions on .dlp files. | -| ohos.permission.PROVISIONING_MESSAGE | system_core | system_grant | TRUE | Allows the Super Device Manager application to be activated. | -| ohos.permission.
ACCESS_SYSTEM_SETTINGS | system_basic | system_grant | TRUE | Allows an app to access or start system **Settings**. | -| ohos.permission.READ_IMAGEVIDEO | system_basic | user_grant | TRUE | Allows access to the images or video files in a user's directory. | -| ohos.permission.READ_AUDIO | system_basic | user_grant | TRUE | Allows access to the audio files in a user's directory. | -| ohos.permission.READ_DOCUMENT | system_basic | user_grant | TRUE | Allows access to the files in a user's directory. | -| ohos.permission.WRITE_IMAGEVIDEO | system_basic | user_grant | TRUE | Allows modification to the images or video files in a user's directory. | -| ohos.permission.WRITE_AUDIO | system_basic | user_grant | TRUE | Audio modification to the audio files in a user's directory. | -| ohos.permission.WRITE_DOCUMENT | system_basic | user_grant | TRUE | Allows modification to the files in a user's directory. | -| ohos.permission.
ABILITY_BACKGROUND_COMMUNICATION | system_basic | system_grant | TRUE | Allows an app to start the Ability component in the background and establish a connection with it. | -| ohos.permission.
securityguard.REPORT_SECURITY_INFO | system_basic | system_grant | FALSE | Allows an app to report risk data for security guard. | -| ohos.permission.
securityguard.REQUEST_SECURITY_MODEL_RESULT | system_basic | system_grant | TRUE | Allows an app to obtain the device risk status. | -| ohos.permission.
securityguard.REQUEST_SECURITY_EVENT_INFO | system_core | system_grant | FALSE | Allows an app to obtain detailed risk data. | -| ohos.permission.
READ_ACCESSIBILITY_CONFIG | system_basic | system_grant | FALSE | Allows an app to read the accessibility configuration. | -| ohos.permission.
WRITE_ACCESSIBILITY_CONFIG | system_basic | system_grant | FALSE | Allows an app to set the accessibility configuration. | -| ohos.permission.
ACCESS_CERT_MANAGER_INTERNAL | system_basic | system_grant | FALSE | Allows an app to install, uninstall, enable, and disable certificates and credentials. | -| ohos.permission.
ACCESS_CERT_MANAGER | normal | system_grant | FALSE | Allows an app to manage private credentials and query certificate status. | -| ohos.permission.
ACCESS_PUSH_SERVICE | system_basic | system_grant | TRUE | Allows an app to to access the Ability of the push service. | -| ohos.permission.
RECEIVER_STARTUP_COMPLETED | system_basic | system_grant | FALSE | Allows an app to subscribe to the startup broadcast. | -| ohos.permission.
MANAGE_CAMERA_CONFIG | system_basic | system_grant | FALSE | Allows an app to enable or disable cameras globally. | -| ohos.permission.READ_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | Allows an app to read all calendar information. | -| ohos.permission.WRITE_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | Allows an app to add, remove, or change all calendar events. | -| ohos.permission.ENFORCE_USER_IAM | system_core | system_grant | TRUE | Allows an SA to delete user information from the IAM subsystem without a token. | -| ohos.permission.ACCESS_AUTH_RESPOOL | system_core | system_grant | TRUE | Allows an SA to register the executor. | -| ohos.permission.MOUNT_UNMOUNT_MANAGER | system_basic | system_grant | FALSE | Allows an app to mount and unmount external cards. | -| ohos.permission.MOUNT_FORMAT_MANAGER | system_basic | system_grant | FALSE | Allows an app to format external cards. | -| ohos.permission.STORAGE_MANAGER | system_basic | system_grant | TRUE | Allows an app to call the interfaces of the Storage Manager service to query space statistics and volume information. | -| ohos.permission.BACKUP | system_basic | system_grant | TRUE | Allows an app to have backup and restore capabilities. | -| ohos.permission.FILE_ACCESS_MANAGER | system_basic | system_grant | TRUE | Allows a file management app to access user data files through the FAF. | -| ohos.permission.MANAGE_AUDIO_CONFIG | system_basic | system_grant | TRUE | Allows an app to to mute microphones globally. | +# Application Permission List + +Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine the permissions required for your application. + +For details about how to apply for required permissions, see [Permission Application Guide](accesstoken-guidelines.md). + +## ohos.permission.USE_BLUETOOTH + +Allows an application to access Bluetooth configurations. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISCOVER_BLUETOOTH + +Allows an application to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_BLUETOOTH + +Allows an application to pair with a Bluetooth device and access the contacts or messages of the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERNET + +Allows an application to access the Internet. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MODIFY_AUDIO_SETTINGS + +Allows an application to modify audio settings. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_NOTIFICATION_POLICY + +Allows an application to access the notification policy on the device. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.GET_TELEPHONY_STATE + +Allows an application to read telephony information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REQUIRE_FORM + +Allows an application to obtain widgets. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_NETWORK_INFO + +Allows an application to obtain network information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PLACE_CALL + +Allows an application to make calls without starting the dialer. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_NETWORK_INFO + +Allows an application to set data network information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REMOVE_CACHE_FILES + +Allows the cache of the specified application to be cleared. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REBOOT + +Allows an application to restart the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUNNING_LOCK + +Allows an application to obtain a running lock. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TIME + +Allows an application to set the system time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TIME_ZONE + +Allows an application to set the system time zone. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DOWNLOAD_SESSION_MANAGER + +Allows an application to manage download sessions. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.COMMONEVENT_STICKY + +Allows an application to publish sticky common events. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SYSTEM_FLOAT_WINDOW + +Allows an application to be displayed in a floating window on top of other applications. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PRIVACY_WINDOW + +Allows an application to set screens that cannot be captured or recorded. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.POWER_MANAGER + +Allows an application to hibernate or wake up the device by calling an API. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REFRESH_USER_ACTION + +Allows an application to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.POWER_OPTIMIZATION + +Allows an application to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REBOOT_RECOVERY + +Allows an application to restart the device and enter Recovery mode. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_LOCAL_ACCOUNTS + +Allows an application to manage local user accounts. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +Allows access between multiple OS accounts. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.VIBRATE + +Allows an application to control vibration. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECT_IME_ABILITY + +Allows an application to bind the InputMethodAbility. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECT_SCREEN_SAVER_ABILITY + +Allows an application to bind the ScreenSaverAbility. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_SCREEN_SAVER + +Allows an application to read the screen saver information, such as the list of screen savers that have been installed and the activated one. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_SCREEN_SAVER + +Allows an application to modify the screen saver information, such as activating and previewing a screen saver. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WALLPAPER + +Allows an application to set a static wallpaper. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WALLPAPER + +Allows an application to read wallpaper files. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +Allows an application to enable or disable an application or component. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_MISSIONS + +Allows an application to obtain information about running processes and mission in a mission stack. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CLEAN_BACKGROUND_PROCESSES + +Allows an application to clear background processes based on their bundle names. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.KEEP_BACKGROUND_RUNNING + +Allows a Service ability to keep running in the background. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.UPDATE_CONFIGURATION + +Allows an application to modify system settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.UPDATE_SYSTEM + +Allows an application to call the update APIs. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.FACTORY_RESET + +Allows an application to call the API for restoring factory settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GRANT_SENSITIVE_PERMISSIONS + +Allows an application to grant sensitive permissions to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REVOKE_SENSITIVE_PERMISSIONS + +Allows an application to revoke sensitive permissions granted to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_SENSITIVE_PERMISSIONS + +Allows an application to obtain the sensitive permissions that have been granted to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + +Allows an application to set the attributes of applications of other users. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.LISTEN_BUNDLE_CHANGE + +Allows an application to listen for changes in other applications, when they are installed, updated, or uninstalled. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_BUNDLE_INFO + +Allows an application to query information about another application. This permission applies only to third-party applications. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +Allows an application to query information about other applications at the same time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCELEROMETER + +Allows an application to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GYROSCOPE + +Allows an application to read data from a gyroscope sensor or uncalibrated gyroscope sensor. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INSTALL_BUNDLE + +Allows an application to install and uninstall other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_SHORTCUTS + +Allows an application to query and start shortcuts of other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.radio.ACCESS_FM_AM + +Allows an application to access radio services. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TELEPHONY_STATE + +Allows an application to change the telephone state. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.START_ABILIIES_FROM_BACKGROUND + +Allows an application to start Feature abilities in the background. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.BUNDLE_ACTIVE_INFO + +Allows an application to obtain how long other applications have been running in the foreground or background. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.START_INVISIBLE_ABILITY + +Allows an application to start an invisible ability. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.sec.ACCESS_UDID + +Allows an application to obtain the Unified Device ID (UDID). + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.LAUNCH_DATA_PRIVACY_CENTER + +Allows an application to switch from its privacy statement page to the Data & privacy page. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_MEDIA_RESOURCES + +Allows an application to obtain and manage the media resources that are being played on the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PUBLISH_AGENT_REMINDER + +Allows an application to use agent-powered reminders. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONTROL_TASK_SYNC_ANIMATOR + +Allows applications to use sync task animations. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INPUT_MONITORING + +Allows an application to listen for input events. Only the system signed applications can apply for this permission. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_MISSIONS + +Allows an application to manage ability mission stacks. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NOTIFICATION_CONTROLLER + +Allows an application to manage and subscribe to notifications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECTIVITY_INTERNAL + +Allows an application to obtain network information or modify network settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_ABILITY_CONTROLLER + +Allows an application to set the start and stop of an ability. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.USE_USER_IDM + +Allows an application to access the system identity credential information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_USER_IDM + +Allows an application to use the system identity credential management capability to enroll, modify, and delete PINs, face images, and fingerprints. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_BIOMETRIC + +Allows an application to use biometric recognition for identity authentication. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_USER_AUTH_INTERNAL + +Allows an application to use the system identity authentication capability to authenticate or identify users. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_PIN_AUTH + +Allows a system application to call the PIN input APIs to present a password input dialog box for users. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.GET_RUNNING_INFO + +Allows an application to obtain running status information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CLEAN_APPLICATION_DATA + +Allows an application to clear application data. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUNNING_STATE_OBSERVER + +Allows an application to observe the application status. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CAPTURE_SCREEN + +Allows an application to take screenshots. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_INFO + +Allows an application to obtain WLAN information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_INFO_INTERNAL + +Allows an application to obtain WLAN information. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WIFI_INFO + +Allows an application to set WLAN devices. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_PEERS_MAC + +Allows an application to obtain the MAC address of the peer WLAN or Bluetooth device. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_LOCAL_MAC + +Allows an application to obtain the MAC address of the local WLAN or Bluetooth device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_CONFIG + +Allows an application to obtain the WLAN configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WIFI_CONFIG + +Allows an application to set WLAN information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_WIFI_CONNECTION + +Allows an application to manage WLAN connections. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_WIFI_HOTSPOT + +Allows an application to enable or disable Wi-Fi hotspots. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_ALL_APP_ACCOUNTS + +Allows an application to obtain all application account information. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_SECURE_SETTINGS + +Allows an application to modify security settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_DFX_SYSEVENT + +Allows an application to access system event logging data. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +Allows an application to activate the device administrator app. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_ENTERPRISE_INFO + +Allows the device administrator application to set enterprise information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT + +Allows the device administrator application to subscribe to management events. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_SET_DATETIME + +Allows the device administrator application to set the system time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_GET_DEVICE_INFO + +Allows the device administrator application to obtain device information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NFC_TAG + +Allows an application to read NFC tag information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.NFC_CARD_EMULATION + +Allows an application to implement card emulation. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.PERMISSION_USED_STATS + +Allows a system application to access the permission usage records. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +Allows an application to send agent-powered notifications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ANSWER_CALL + +Allows an application to answer incoming calls. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CALENDAR + +Allows an application to read calendar data. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CALL_LOG + +Allows an application to read call logs. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CELL_MESSAGES + +Allows an application to read cell broadcast messages received by the device. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CONTACTS + +Allows an application to read contacts. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_MESSAGES + +Allows an application to read messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_MMS + +Allows an application to receive and process MMS messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_SMS + +Allows an application to receive and process SMS messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_WAP_MESSAGES + +Allows an application to receive and process WAP messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.MICROPHONE + +Allows an application to access the microphone. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.SEND_MESSAGES + +Allows an application to send messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CALENDAR + +Allows an application to add, remove, and modify calendar events. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CALL_LOG + +Allows an application to add, remove, and modify call logs. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CONTACTS + +Allows an application to add, remove, and modify contacts. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISTRIBUTED_DATASYNC + +Allows an application to exchange data with other devices. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_VOICEMAIL + +Allows an application to leave messages in the voice mailbox. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.LOCATION_IN_BACKGROUND + +Allows an application running in the background to obtain the device location. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: FALSE + +## ohos.permission.LOCATION + +Allows an application to obtain the device location. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.APPROXIMATELY_LOCATION + +Allows an application to obtain the approximate location information of a device. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: FALSE + +## ohos.permission.MEDIA_LOCATION + +Allow an application to access geographical locations in the user's media file. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.CAMERA + +Allows an application to use the camera to take photos and record videos. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_MEDIA + +Allows an application to read media files from the user's external storage. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_MEDIA + +Allows an application to read media files from and write media files into the user's external storage. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACTIVITY_MOTION + +Allows an application to read the current workout status of the user. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_HEALTH_DATA + +Allows an application to read the health data of the user. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_DEFAULT_APPLICATION + +Allows an application to query default applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_DEFAULT_APPLICATION + +Allows an application to set and reset default applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_DISPOSED_APP_STATUS + +Allows an application to set and query the application handling state. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_IDS + +Allows an application to query the unique identifier of a device. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DUMP + +Allows the basic system information and SA service information to be exported. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISTRIBUTED_SOFTBUS_CENTER + +Allows networking between different devices. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_DLP_FILE + +Allows configuration and management of the permissions on .dlp files. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PROVISIONING_MESSAGE + +Allows the Super Device Manager application to be activated. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_SYSTEM_SETTINGS + +Allows an application to access or start system **Settings**. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_IMAGEVIDEO + +Allows access to the images or video files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_AUDIO + +Allows access to the audio files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_DOCUMENT + +Allows access to the files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_IMAGEVIDEO + +Allows modification to the images or video files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_AUDIO + +Audio modification to the audio files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_DOCUMENT + +Allows modification to the files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ABILITY_BACKGROUND_COMMUNICATION + +Allows an application to start the Ability component in the background and establish a connection with it. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.securityguard.REPORT_SECURITY_INFO + +Allows an application to report risk data for security guard. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.securityguard.REQUEST_SECURITY_MODEL_RESULT + +Allows an application to obtain the device risk status. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO + +Allows an application to obtain detailed risk data. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.READ_ACCESSIBILITY_CONFIG + +Allows an application to read the accessibility configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.WRITE_ACCESSIBILITY_CONFIG + +Allows an application to set the accessibility configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_CERT_MANAGER_INTERNAL + +Allows an application to install, uninstall, enable, and disable certificates and credentials. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_CERT_MANAGER + +Allows an application to manage private credentials and query certificate status. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_PUSH_SERVICE + +Allows an application to to access the Ability of the push service. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVER_STARTUP_COMPLETED + +Allows an application to subscribe to the startup broadcast. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_CAMERA_CONFIG + +Allows an application to enable or disable cameras globally. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.READ_WHOLE_CALENDAR + +Allows an application to read all calendar information. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_WHOLE_CALENDAR + +Allows an application to add, remove, or change all calendar events. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENFORCE_USER_IAM + +Allows an SA to delete user information from the IAM subsystem without a token. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_AUTH_RESPOOL + +Allows an SA to register the executor. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MOUNT_UNMOUNT_MANAGER + +Allows an application to mount and unmount external cards. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MOUNT_FORMAT_MANAGER + +Allows an application to format external cards. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.STORAGE_MANAGER + +Allows an application to call the interfaces of the Storage Manager service to query space statistics and volume information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.BACKUP + +Allows an application to have backup and restore capabilities. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.FILE_ACCESS_MANAGER + +Allows a file management application to access user data files through the FAF. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_AUDIO_CONFIG + +Allows an application to to mute microphones globally. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_SERVICE_DM + +Allows a system application to obtain the authentication and networking capability of distributed devices. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUN_ANY_CODE + +Allows an application to run unsigned code. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PUBLISH_SYSTEM_COMMON_EVENT + +Allows an application to publish system common events. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE diff --git a/en/contribute/OpenHarmony-security-test-guide.md b/en/contribute/OpenHarmony-security-test-guide.md index 074d90c0ca35d2f83f3effe205ce55660c276c1d..5b6365eaf49d50bb5759a83fb23d5e130bc0587d 100644 --- a/en/contribute/OpenHarmony-security-test-guide.md +++ b/en/contribute/OpenHarmony-security-test-guide.md @@ -1,28 +1,43 @@ -# OpenHarmony Secure Test Guide -With reference to industry standards and best practices, this document provides guidelines for secure tests. +# OpenHarmony Security Test Guide +With reference to industry standards and best practices, this document provides specifications for security tests of the OpenHarmony project. +## Security Test Content -## Secure Coding Test +- Review the code of each module according to [OpenHarmony C&C++ Secure Coding Guide](OpenHarmony-c-cpp-secure-coding-guide.md) and fix all issues found in the review. -1. Review the code of each module, and ensure that the code complies with the [Coding Style](./code-contribution.md#coding-style). +- Use the OpenHarmony gated check-in to scan your code and clear all alarms. -2. Use a dedicated tool to scan the code and ensure all the alarms are cleared. A secure code scanning tool has been integrated in the OpenHarmony gated check-in. +- Use the compilation option scanning tool to scan your binary file and ensure that the settings of all the compilation options comply with the [OpenHarmony Compilation Specifications]. +- For the module that receives and processes user-mode parameters, develop gray-box and white-box fuzz testing suites according to the [Fuzz Testing Guide](https://gitee.com/openharmony/test_developertest/tree/master/libs/fuzzlib) and complete the tests. -## Security Design Verification +- Use mainstream vulnerability scanning tools to scan open-source components. Ensure that all the detected vulnerabilities have been fixed according to the vulnerability management process of the community. -Review and verify the security design of each module, and ensure that the security design complies with [OpenHarmony Security Design Specifications](./OpenHarmony-security-design-guide.md). +- Perform consistency check of the released versions, and check that the [released version images](../release-notes/Readme.md) provide the SAH-256 checksum. +- Complete the security design self-check for each module according to [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md). Ensure that all design issues found in the self-check have been fixed. +- Use mainstream viruses scanning software to scan software packages. Ensure that all virus detected have been removed or confirmed as false alarms. -## Security Tests +- Search for ".cer" and ".pem" or keyword such as "PRIVATE KEY" to find the certificate key, and check that the certificate key is within the validity period and the encryption algorithm meets [encryption algorithm requirements](OpenHarmony-security-design-guide.md#3-encryption). Ensure that all certificate key issues have been resolved. -1. For critical modules, develop graybox and whitebox fuzzing test suites based on the [Fuzzing Test Framework](https://gitee.com/openharmony/test_developertest/tree/master/libs/fuzzlib) and complete the tests. +- Perform black-box fuzz testing on exposed user-mode APIs, including system service APIs, kernel driver APIs, socket APIs, and more. -2. Perform blackbox fuzzing tests on exposed user-mode APIs, including system service APIs, kernel driver APIs, socket network APIs, and more. -3. Use a build scanning tool to check the build option settings. The build files must comply with the OpenHarmony Build Specifications. +>**NOTE** +> +>The preceding requirements apply to all new and inherited features. -4. Use the mainstream vulnerability scanning tools to scan open-source components. Ensure that all the detected vulnerabilities have been fixed according to the vulnerability management process of the community. +## Security Test Completion Requirements +The mandatory security test performed before version release is complete only when: + +- All the security tests mentioned in [Security Test Content](#security-test-content) are complete. + +- All security issues have been closed. + +## Security Test Report Template + +- The security test report must contain the security test results in [Security Test Content](#security-test-content) and pending security issues. +- The version security test report is released with the entire test report of the version, instead of being released and archived separately. diff --git a/en/device-dev/subsystems/subsys-app-privilege-config-guide.md b/en/device-dev/subsystems/subsys-app-privilege-config-guide.md index c795eb7d773cc6b37fed2dbf01582247e52e92be..665652b23e1832716680e14d5552c66aec744062 100644 --- a/en/device-dev/subsystems/subsys-app-privilege-config-guide.md +++ b/en/device-dev/subsystems/subsys-app-privilege-config-guide.md @@ -24,7 +24,7 @@ General application privileges are privileges available to applications on all t ### Configuration -1. In the [HarmonyAppProvision file](https://gitee.com/openharmony/docs/blob/master/en/application-dev/quick-start/app-provision-structure.md), configure the general privileges in the **app-privilege-capabilities** field. +1. In the [HarmonyAppProvision file](../../application-dev/security/app-provision-structure.md), configure the general privileges in the **app-privilege-capabilities** field. 2. Use the signing tool hapsigner to sign the HarmonyAppProvision file and generate a **.p7b** file. 3. Use the **.p7b** file to sign the HAP. diff --git a/en/readme/distributed-data-management.md b/en/readme/distributed-data-management.md index ef0edbcf9a426b7a59a1eb0f60caa6940bf65a77..9c60ec0f0390dde3369de5e7cc6e8bfb10b2817c 100644 --- a/en/readme/distributed-data-management.md +++ b/en/readme/distributed-data-management.md @@ -5,7 +5,7 @@ **Distributed Data Management Subsystem** -The Distributed Data Management subsystem can persistently store various structured data of a single device and also supports data synchronization and sharing across devices. With the Distributed Data Management subsystem, application data can be seamlessly processed across different devices, ensuring consistent user experience for the same application across devices. +The Distributed Data Management subsystem can persistently store various structured data of a single device. It also supports data synchronization and sharing across devices. With the Distributed Data Management subsystem, application data can be seamlessly processed across devices, ensuring consistent user experience for the same application across devices. **Subsystem Architecture** @@ -47,15 +47,15 @@ The **DataShare** module allows an application to manage its own data and share ### DDS -The Distributed Data Service (DDS) implements distributed database collaboration across devices for applications. The DDS isolates data based on a triplet of the account, application, and database. The DDS synchronizes data between trusted devices to provide users with consistent data access experience on different devices. +The Distributed Data Service (DDS) implements database collaboration across devices for applications. The DDS isolates data based on a triplet of the account, application, and database. The DDS synchronizes data between trusted devices, delivering a consistent data access experience on different devices. ### Preferences -The **Preferences** module allows quick access to data in KV pairs and storage of a small amount of data for local applications. The data is stored in local files and loaded in memory, which allows faster access and higher processing efficiency. Preferences provide non-relational data storage and are not suitable for storing a large amount of data. +The **Preferences** module allows quick access to data in KV pairs and storage of a small amount of data for local applications. The data is stored in local files in KV pairs and loaded in memory, which allows for faster access and higher processing efficiency. Preferences provide non-relational data storage and are not suitable for storing a large amount of data. 1. The **Preferences** module provides APIs for **preferences** operations. -2. You can use **getPreferences()** to load the content of a specified file to a **Preferences** instance. Each file has only one **Preferences** instance. The system stores the instance data in memory through a static container until the app removes the instance from the memory or deletes the file. -3. After obtaining a **Preferences** instance, the app can call the APIs in **Preferences** to read data from or write data to the **Preferences** instance, and call **flush()** to save the instance data to a file. +2. You can use **getPreferences()** to load the content of a specified file to a **Preferences** instance. Each file has only one **Preferences** instance. The system stores the instance data in memory through a static container until the application removes the instance from the memory or deletes the file. +3. After obtaining a **Preferences** instance, the application can call the APIs of **Preferences** to read data from or write data to the **Preferences** instance, and call **flush()** to save the instance data to a file. ### RDB Store diff --git a/zh-cn/application-dev/database/database-mdds-guidelines.md b/zh-cn/application-dev/database/database-mdds-guidelines.md index fd675ecb1116f6a0259f1e840047e606e30d1654..21b949d08dd54a5c1d33d30a0934feb9af27f386 100644 --- a/zh-cn/application-dev/database/database-mdds-guidelines.md +++ b/zh-cn/application-dev/database/database-mdds-guidelines.md @@ -14,7 +14,7 @@ | 接口名称 | 描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | | createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | 创建一个`KVManager`对象实例,用于管理数据库对象。 | -| getKVStore<TextendsKVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<TextendsKVStore>(storeId: string, options: Options): Promise<T> | 指定`Options`和`storeId`,创建并获取指定类型`KVStore`数据库。 | +| getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | 指定`Options`和`storeId`,创建并获取指定类型`KVStore`数据库。 | | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | 插入和更新数据。 | | delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | 删除数据。 | | get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | 查询数据。 | @@ -71,22 +71,22 @@ import UIAbility from '@ohos.app.ability.UIAbility'; let context = null; - - function grantPermission() { - class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { let context = this.context; - } + } } - - let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; - context.requestPermissionsFromUser(permissions).then((data) => { + + function grantPermission() { + let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { console.log('success: ${data}'); - }).catch((error) => { + }).catch((error) => { console.log('failed: ${error}'); - }); + }); } - + grantPermission(); ``` diff --git a/zh-cn/application-dev/device/device-location-geocoding.md b/zh-cn/application-dev/device/device-location-geocoding.md deleted file mode 100644 index 32892d089c9c587b1efcfd6aafcb62fa98e96d74..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/device/device-location-geocoding.md +++ /dev/null @@ -1,91 +0,0 @@ -# (逆)地理编码转化 - - -## 场景介绍 - -使用坐标描述一个位置,非常准确,但是并不直观,面向用户表达并不友好。系统向开发者提供了以下两种转化能力。 - -- 地理编码转化:将地理描述转化为具体坐标。 - -- 逆地理编码转化能力:将坐标转化为地理描述。 - -其中地理编码包含多个属性来描述位置,包括国家、行政区划、街道、门牌号、地址描述等等,这样的信息更便于用户理解。 - - -## 接口说明 - -进行坐标和地理编码信息的相互转化,所使用的接口说明如下,详细信息参见:[位置服务](../reference/apis/js-apis-geoLocationManager.md)。 - - **表1** 地理编码转化能力和逆地理编码转化能力的API功能介绍 - -| 接口名 | 功能描述 | -| -------- | -------- | -| isGeocoderAvailable(): boolean; | 判断(逆)地理编码服务状态。 | -| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | 调用逆地理编码服务,将坐标转换为地理描述,使用callback回调异步返回结果。 | -| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>> | 调用逆地理编码服务,将坐标转换为地理描述,使用Promise方式异步返回结果。 | -| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | 调用地理编码服务,将地理描述转换为具体坐标,使用callback回调异步返回结果。 | -| getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> | 调用地理编码服务,将地理描述转换为具体坐标,使用Promise方式异步返回结果。 | - - -## 开发步骤 - -> **说明:** -> GeoConvert需要访问后端服务,请确保设备联网,以进行信息获取。 - -1. 导入geoLocationManager模块,所有与(逆)地理编码转化能力相关的功能API,都是通过该模块提供的。 - - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - ``` - -2. 查询geoCoder服务是否可用。 - - 调用isGeoServiceAvailable查询geoCoder服务是否可用,如果服务可用再继续进行步骤3。 - - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - try { - var isAvailable = geoLocationManager.isGeocoderAvailable(); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - -3. 获取转化结果。 - - 调用getAddressesFromLocation,坐标转化地理位置信息。 - - ```ts - var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; - try { - geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); - } - }); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - 参考接口API说明[位置服务](../reference/apis/js-apis-geoLocationManager.md),应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。 - - 调用getAddressesFromLocationName位置描述转化坐标。 - - ```ts - var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; - try { - geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); - } - }); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - 参考接口API说明[位置服务](../reference/apis/js-apis-geoLocationManager.md),应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。 - - 如果需要查询的位置描述可能出现多地重名的请求,可以设置GeoCodeRequest,通过设置一个经纬度范围,以高效地获取期望的准确结果。 diff --git a/zh-cn/application-dev/device/device-location-info.md b/zh-cn/application-dev/device/device-location-info.md deleted file mode 100644 index 10f006b399671f5c5047299dd3f6e2a72925d20f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/device/device-location-info.md +++ /dev/null @@ -1,146 +0,0 @@ -# 获取设备的位置信息 - - -## 场景介绍 - -开发者可以调用OpenHarmony位置相关接口,获取设备实时位置,或者最近的历史位置。 - -对于位置敏感的应用业务,建议获取设备实时位置信息。如果不需要设备实时位置信息,并且希望尽可能的节省耗电,开发者可以考虑获取最近的历史位置。 - - -## 接口说明 - -获取设备的位置信息,所使用的接口说明参见:[位置服务](../reference/apis/js-apis-geoLocationManager.md)。 - - -## 开发步骤 - -如需要获取设备位置相关接口信息,请参考[位置服务](../reference/apis/js-apis-geoLocationManager.md)。 - -1. 应用在使用系统能力前,需要检查是否已经获取用户授权访问设备位置信息。如未获得授权,可以向用户申请需要的位置权限,申请方式请参考下文。 - 系统提供的定位权限有: - - ohos.permission.LOCATION - - - ohos.permission.APPROXIMATELY_LOCATION - - - ohos.permission.LOCATION_IN_BACKGROUND - - 访问设备的位置信息,必须申请权限,并且获得用户授权。 - - API9之前的版本,申请ohos.permission.LOCATION即可。 - - API9及之后的版本,需要申请ohos.permission.APPROXIMATELY_LOCATION或者同时申请ohos.permission.APPROXIMATELY_LOCATION和ohos.permission.LOCATION;无法单独申请ohos.permission.LOCATION。 - - | target API level | 申请位置权限 | 申请结果 | 位置的精确度 | - | -------- | -------- | -------- | -------- | - | 小于9 | ohos.permission.LOCATION | 成功 | 获取到精准位置,精准度在米级别。 | - | 大于等于9 | ohos.permission.LOCATION | 失败 | 无法获取位置。 | - | 大于等于9 | ohos.permission.APPROXIMATELY_LOCATION | 成功 | 获取到模糊位置,精确度为5公里。 | - | 大于等于9 | ohos.permission.APPROXIMATELY_LOCATION和ohos.permission.LOCATION | 成功 | 获取到精准位置,精准度在米级别。 | - - 如果应用在后台运行时也需要访问设备位置,除需要将应用声明为允许后台运行外,还必须申请ohos.permission.LOCATION_IN_BACKGROUND权限,这样应用在切入后台之后,系统可以继续上报位置信息。 - - 开发者可以在应用配置文件中声明所需要的权限,具体可参考[授权申请指导](../security/accesstoken-guidelines.md)。 - -2. 导入geoLocationManager模块,所有与基础定位能力相关的功能API,都是通过该模块提供的。 - - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - ``` - -3. 实例化LocationRequest对象,用于告知系统该向应用提供何种类型的位置服务,以及位置结果上报的频率。
- **方式一:** - - 为了面向开发者提供贴近其使用场景的API使用方式,系统定义了几种常见的位置能力使用场景,并针对使用场景做了适当的优化处理,应用可以直接匹配使用,简化开发复杂度。系统当前支持场景如下表所示。 - - - ```ts - export enum LocationRequestScenario { - UNSET = 0x300, - NAVIGATION, - TRAJECTORY_TRACKING, - CAR_HAILING, - DAILY_LIFE_SERVICE, - NO_POWER, - } - ``` - - - **表2** 定位场景类型说明 - - | 场景名称 | 常量定义 | 说明 | - | ------------ | ------------------- | ------------------------------------------------------------ | - | 导航场景 | NAVIGATION | 适用于在户外定位设备实时位置的场景,如车载、步行导航。在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务,结合场景特点,在导航启动之初,用户很可能在室内、车库等遮蔽环境,GNSS技术很难提供位置服务。为解决此问题,我们会在GNSS提供稳定位置结果之前,使用系统网络定位技术,向应用提供位置服务,以在导航初始阶段提升用户体验。
此场景默认以最小1秒间隔上报定位结果,使用此场景的应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | - | 轨迹跟踪场景 | TRAJECTORY_TRACKING | 适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。
此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | - | 出行约车场景 | CAR_HAILING | 适用于用户出行打车时定位当前位置的场景,如网约车类应用。
此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | - | 生活服务场景 | DAILY_LIFE_SERVICE | 生活服务场景,适用于不需要定位用户精确位置的使用场景,如新闻资讯、网购、点餐类应用,做推荐、推送时定位用户大致位置即可。
此场景默认以最小1秒间隔上报定位结果,并且应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。 | - | 无功耗场景 | NO_POWER | 无功耗场景,适用于不需要主动启动定位业务。系统在响应其他应用启动定位业务并上报位置结果时,会同时向请求此场景的应用程序上报定位结果,当前的应用程序不产生定位功耗。
此场景默认以最小1秒间隔上报定位结果,并且应用需要申请ohos.permission.LOCATION权限,同时获得用户授权。 | - - 以导航场景为例,实例化方式如下: - - ```ts - var requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - ``` - - **方式二:** - - 如果定义的现有场景类型不能满足所需的开发场景,系统提供了基本的定位优先级策略类型。 - - - ```ts - export enum LocationRequestPriority { - UNSET = 0x200, - ACCURACY, - LOW_POWER, - FIRST_FIX, - } - ``` - - - **表3** 定位优先级策略类型说明: - - | 策略类型 | 常量定义 | 说明 | - | ------------------ | -------------- | ------------------------------------------------------------ | - | 定位精度优先策略 | ACCURACY | 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。
应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | - | 快速定位优先策略 | FAST_FIRST_FIX | 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。
应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | - | 低功耗定位优先策略 | LOW_POWER | 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。
应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。 | - - 以定位精度优先策略为例,实例化方式如下: - - ```ts - var requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - ``` - -4. 实例化Callback对象,用于向系统提供位置上报的途径。 - 应用需要自行实现系统定义好的回调接口,并将其实例化。系统在定位成功确定设备的实时位置结果时,会通过该接口上报给应用。应用程序可以在接口的实现中完成自己的业务逻辑。 - - ```ts - var locationChange = (location) => { - console.log('locationChanger: data: ' + JSON.stringify(location)); - }; - ``` - -5. 启动定位。 - - ```ts - geoLocationManager.on('locationChange', requestInfo, locationChange); - ``` - -6. (可选)结束定位。 - - ```ts - geoLocationManager.off('locationChange', locationChange); - ``` - -如果应用使用场景不需要实时的设备位置,可以获取系统缓存的最近一次历史定位结果。 - - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - try { - var location = geoLocationManager.getLastLocation(); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - 此接口的使用需要应用向用户申请ohos.permission.LOCATION权限。 \ No newline at end of file diff --git a/zh-cn/application-dev/device/device-location-overview.md b/zh-cn/application-dev/device/device-location-overview.md deleted file mode 100644 index b955a1a06d6b9b71b47d012f9a1c6fe14627fd47..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/device/device-location-overview.md +++ /dev/null @@ -1,45 +0,0 @@ -# 位置开发概述 - - -移动终端设备已经深入人们日常生活的方方面面,如查看所在城市的天气、新闻轶事、出行打车、旅行导航、运动记录。这些习以为常的活动,都离不开定位用户终端设备的位置。 - - -当用户处于这些丰富的使用场景中时,系统的位置能力可以提供实时准确的位置数据。对于开发者,设计基于位置体验的服务,也可以使应用的使用体验更贴近每个用户。 - - -当应用在实现基于设备位置的功能时,如:驾车导航,记录运动轨迹等,可以调用该模块的API接口,完成位置信息的获取。 - - -## 基本概念 - -位置能力用于确定用户设备在哪里,系统使用位置坐标标示设备的位置,并用多种定位技术提供服务,如GNSS定位、基站定位、WLAN/蓝牙定位(基站定位、WLAN/蓝牙定位后续统称“网络定位技术”)。通过这些定位技术,无论用户设备在室内或是户外,都可以准确地确定设备位置。 - -- **坐标**
- 系统以1984年世界大地坐标系统为参考,使用经度、纬度数据描述地球上的一个位置。 - -- **GNSS定位**
- 基于全球导航卫星系统,包含:GPS、GLONASS、北斗、Galileo等,通过导航卫星、设备芯片提供的定位算法,来确定设备准确位置。定位过程具体使用哪些定位系统,取决于用户设备的硬件能力。 - -- **基站定位**
- 根据设备当前驻网基站和相邻基站的位置,估算设备当前位置。此定位方式的定位结果精度相对较低,并且需要设备可以访问蜂窝网络。 - -- **WLAN、蓝牙定位**
- 根据设备可搜索到的周围WLAN、蓝牙设备位置,估算设备当前位置。此定位方式的定位结果精度依赖设备周围可见的固定WLAN、蓝牙设备的分布,密度较高时,精度也相较于基站定位方式更高,同时也需要设备可以访问网络。 - - -## 运作机制 - -位置能力作为系统为应用提供的一种基础服务,需要应用在所使用的业务场景,向系统主动发起请求,并在业务场景结束时,主动结束此请求,在此过程中系统会将实时的定位结果上报给应用。 - - -## 约束与限制 - -使用设备的位置能力,需要用户进行确认并主动开启位置开关。如果位置开关没有开启,系统不会向任何应用提供位置服务。 - -设备位置信息属于用户敏感数据,所以即使用户已经开启位置开关,应用在获取设备位置前仍需向用户申请位置访问权限。在用户确认允许后,系统才会向应用提供位置服务。 - -## 相关实例 - -针对位置服务,有以下相关实例可供参考: - -- [`Location`:位置服务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location) diff --git a/zh-cn/application-dev/device/location-guidelines.md b/zh-cn/application-dev/device/location-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..47da8c123b8e47f3533f765f115cd3593606145c --- /dev/null +++ b/zh-cn/application-dev/device/location-guidelines.md @@ -0,0 +1,409 @@ +# 位置服务开发指南 + +## 位置服务开发概述 + +移动终端设备已经深入人们日常生活的方方面面,如查看所在城市的天气、新闻轶事、出行打车、旅行导航、运动记录。这些习以为常的活动,都离不开定位用户终端设备的位置。 + +当用户处于这些丰富的使用场景中时,系统的位置能力可以提供实时准确的位置数据。对于开发者,设计基于位置体验的服务,也可以使应用的使用体验更贴近每个用户。 + +当应用在实现基于设备位置的功能时,如:驾车导航,记录运动轨迹等,可以调用该模块的API接口,完成位置信息的获取。 + +### 位置服务简介 + +位置子系统使用多种定位技术提供服务,如GNSS定位、基站定位、WLAN/蓝牙定位(基站定位、WLAN/蓝牙定位后续统称“网络定位技术”);通过这些定位技术,无论用户设备在室内或是户外,都可以准确地确定设备位置。 + +位置服务除了提供基础的定位服务之外,还提供了地理围栏、地理编码、逆地理编码、国家码等功能和接口。 + +- **坐标**
+ 系统以1984年世界大地坐标系统为参考,使用经度、纬度数据描述地球上的一个位置。 + +- **GNSS定位**
+ 基于全球导航卫星系统,包含:GPS、GLONASS、北斗、Galileo等,通过导航卫星、设备芯片提供的定位算法,来确定设备准确位置。定位过程具体使用哪些定位系统,取决于用户设备的硬件能力。 + +- **基站定位**
+ 根据设备当前驻网基站和相邻基站的位置,估算设备当前位置。此定位方式的定位结果精度相对较低,并且需要设备可以访问蜂窝网络。 + +- **WLAN、蓝牙定位**
+ 根据设备可搜索到的周围WLAN、蓝牙设备位置,估算设备当前位置。此定位方式的定位结果精度依赖设备周围可见的固定WLAN、蓝牙设备的分布,密度较高时,精度也相较于基站定位方式更高,同时也需要设备可以访问网络。 + +### 运作机制 + +位置能力作为系统为应用提供的一种基础服务,需要应用在所使用的业务场景,向系统主动发起请求,并在业务场景结束时,主动结束此请求,在此过程中系统会将实时的定位结果上报给应用。 + +### 约束与限制 + +使用设备的位置能力,需要用户进行确认并主动开启位置开关。如果位置开关没有开启,系统不会向任何应用提供位置服务。 + +设备位置信息属于用户敏感数据,所以即使用户已经开启位置开关,应用在获取设备位置前仍需向用户申请位置访问权限。在用户确认允许后,系统才会向应用提供位置服务。 + +### 相关实例 + +针对位置服务,有以下相关实例可供参考: + +- [`Location`:位置服务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location) + + +## 申请位置权限开发指导 + +### 场景概述 + +应用在使用位置服务系统能力前,需要检查是否已经获取用户授权访问设备位置信息。如未获得授权,可以向用户申请需要的位置权限。 + +系统提供的定位权限有: + +- ohos.permission.LOCATION:用于获取精准位置,精准度在米级别。 + +- ohos.permission.APPROXIMATELY_LOCATION:用于获取模糊位置,精确度为5公里。 + +- ohos.permission.LOCATION_IN_BACKGROUND:用于应用切换到后台仍然需要获取定位信息的场景。 + +访问设备的位置信息,必须申请权限,并且获得用户授权。 + +**表1** 位置权限申请方式介绍 + +| target API level | 申请位置权限 | 申请结果 | 位置的精确度 | +| -------- | -------- | -------- | -------- | +| 小于9 | ohos.permission.LOCATION | 成功 | 获取到精准位置,精准度在米级别。 | +| 大于等于9 | ohos.permission.LOCATION | 失败 | 无法获取位置。 | +| 大于等于9 | ohos.permission.APPROXIMATELY_LOCATION | 成功 | 获取到模糊位置,精确度为5公里。 | +| 大于等于9 | 同时申请ohos.permission.APPROXIMATELY_LOCATION和ohos.permission.LOCATION | 成功 | 获取到精准位置,精准度在米级别。 | + +如果应用在后台运行时也需要访问设备位置,除需要将应用声明为允许后台运行外,还必须申请ohos.permission.LOCATION_IN_BACKGROUND权限,这样应用在切入后台之后,系统可以继续上报位置信息。 + +开发者可以在应用配置文件中声明所需要的权限,具体可参考[授权申请指导](../security/accesstoken-guidelines.md)。 + +位置服务每个接口需要申请哪些权限可以参见如下文档:[位置服务](../reference/apis/js-apis-geoLocationManager.md)。 + +### 开发步骤 + +具体可参考[授权申请指导](../security/accesstoken-guidelines.md)。 + + +## 获取设备的位置信息开发指导 + +### 场景概述 + +开发者可以调用OpenHarmony位置相关接口,获取设备实时位置,或者最近的历史位置。 + +对于位置敏感的应用业务,建议获取设备实时位置信息。如果不需要设备实时位置信息,并且希望尽可能的节省耗电,开发者可以考虑获取最近的历史位置。 + +### 接口说明 + +获取设备的位置信息所使用的接口如下,详细说明参见:[位置服务](../reference/apis/js-apis-geoLocationManager.md)。 + +**表2** 获取设备的位置信息接口介绍 + +| 接口名 | 功能描述 | +| -------- | -------- | +| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void | 开启位置变化订阅,并发起定位请求。 | +| off(type: 'locationChange', callback?: Callback<Location>): void | 关闭位置变化订阅,并删除对应的定位请求。 | +| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void | 获取当前位置,使用callback回调异步返回结果。 | +| getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> | 获取当前位置,使用Promise方式异步返回结果。 | +| getLastLocation(): Location | 获取最近一次定位结果。 | + +### 开发步骤 + +1. 获取设备的位置信息,需要有位置权限,位置权限申请的方法和步骤见[申请位置权限开发指导](#申请位置权限开发指导)。 + +2. 导入geoLocationManager模块,所有与基础定位能力相关的功能API,都是通过该模块提供的。 + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + ``` + +3. 实例化LocationRequest对象,用于告知系统该向应用提供何种类型的位置服务,以及位置结果上报的频率。
+ **方式一:** + + 为了面向开发者提供贴近其使用场景的API使用方式,系统定义了几种常见的位置能力使用场景,并针对使用场景做了适当的优化处理,应用可以直接匹配使用,简化开发复杂度。系统当前支持场景如下表所示。 + + ***定位场景类型说明*** + + - 导航场景:NAVIGATION
+ 适用于在户外定位设备实时位置的场景,如车载、步行导航。
在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务,结合场景特点,在导航启动之初,用户很可能在室内、车库等遮蔽环境,GNSS技术很难提供位置服务。
为解决此问题,我们会在GNSS提供稳定位置结果之前,使用系统网络定位技术,向应用提供位置服务,以在导航初始阶段提升用户体验。
此场景默认以最小1秒间隔上报定位结果,使用此场景的应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 + + - 轨迹跟踪场景:TRAJECTORY_TRACKING
+ 适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。
此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 + + - 出行约车场景:CAR_HAILING
+ 适用于用户出行打车时定位当前位置的场景,如网约车类应用。
此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 + + - 生活服务场景:DAILY_LIFE_SERVICE
+ 生活服务场景,适用于不需要定位用户精确位置的使用场景,如新闻资讯、网购、点餐类应用,做推荐、推送时定位用户大致位置即可。
此场景默认以最小1秒间隔上报定位结果,并且应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。 + + - 无功耗场景:NO_POWER
+ 无功耗场景,适用于不需要主动启动定位业务。系统在响应其他应用启动定位业务并上报位置结果时,会同时向请求此场景的应用程序上报定位结果,当前的应用程序不产生定位功耗。
此场景默认以最小1秒间隔上报定位结果,并且应用需要申请ohos.permission.LOCATION权限,同时获得用户授权。 + + + ```ts + export enum LocationRequestScenario { + UNSET = 0x300, + NAVIGATION, + TRAJECTORY_TRACKING, + CAR_HAILING, + DAILY_LIFE_SERVICE, + NO_POWER, + } + ``` + + + 以导航场景为例,实例化方式如下: + + ```ts + let requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + ``` + + **方式二:** + + 如果定义的现有场景类型不能满足所需的开发场景,系统提供了基本的定位优先级策略类型。 + + ***定位优先级策略类型说明*** + + - 定位精度优先策略:ACCURACY
+ 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。 + + - 快速定位优先策略:FIRST_FIX
+ 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。 + + - 低功耗定位优先策略:LOW_POWER
+ 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。 + + ```ts + export enum LocationRequestPriority { + UNSET = 0x200, + ACCURACY, + LOW_POWER, + FIRST_FIX, + } + ``` + + 以定位精度优先策略为例,实例化方式如下: + + ```ts + let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + ``` + +4. 实例化Callback对象,用于向系统提供位置上报的途径。 + 应用需要自行实现系统定义好的回调接口,并将其实例化。系统在定位成功确定设备的实时位置结果时,会通过该接口上报给应用。应用程序可以在接口的实现中完成自己的业务逻辑。 + + ```ts + let locationChange = (location) => { + console.log('locationChanger: data: ' + JSON.stringify(location)); + }; + ``` + +5. 启动定位。 + + ```ts + geoLocationManager.on('locationChange', requestInfo, locationChange); + ``` + +6. (可选)结束定位。 + + 如果不主动结束定位可能导致设备功耗高,耗电快;建议在不需要获取定位信息时及时结束定位。 + + ```ts + geoLocationManager.off('locationChange', locationChange); + ``` + + 如果应用使用场景不需要实时的设备位置,可以获取系统缓存的最近一次历史定位结果。 + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + let location = geoLocationManager.getLastLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## (逆)地理编码转化开发指导 + +### 场景概述 + +使用坐标描述一个位置,非常准确,但是并不直观,面向用户表达并不友好。系统向开发者提供了以下两种转化能力。 + +- 地理编码转化:将地理描述转化为具体坐标。 + +- 逆地理编码转化能力:将坐标转化为地理描述。 + +其中地理编码包含多个属性来描述位置,包括国家、行政区划、街道、门牌号、地址描述等等,这样的信息更便于用户理解。 + +### 接口说明 + +进行坐标和地理编码信息的相互转化,所使用的接口说明如下,详细信息参见:[位置服务](../reference/apis/js-apis-geoLocationManager.md)。 + +**表3** (逆)地理编码转化接口介绍 + +| 接口名 | 功能描述 | +| -------- | -------- | +| isGeocoderAvailable(): boolean; | 判断(逆)地理编码服务状态。 | +| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | 调用逆地理编码服务,将坐标转换为地理描述,使用callback回调异步返回结果。 | +| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>> | 调用逆地理编码服务,将坐标转换为地理描述,使用Promise方式异步返回结果。 | +| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | 调用地理编码服务,将地理描述转换为具体坐标,使用callback回调异步返回结果。 | +| getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> | 调用地理编码服务,将地理描述转换为具体坐标,使用Promise方式异步返回结果。 | + +### 开发步骤 + +> **说明:** +> GeoConvert需要访问后端服务,请确保设备联网,以进行信息获取。 + +1. 导入geoLocationManager模块,所有与(逆)地理编码转化能力相关的功能API,都是通过该模块提供的。 + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + ``` + +2. 查询geoCoder服务是否可用。 + - 调用isGeoServiceAvailable查询geoCoder服务是否可用,如果服务可用再继续进行步骤3。 + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + let isAvailable = geoLocationManager.isGeocoderAvailable(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +3. 获取转化结果。 + - 调用getAddressesFromLocation,坐标转化地理位置信息。 + + ```ts + let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); + } else { + console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + 参考接口API说明[位置服务](../reference/apis/js-apis-geoLocationManager.md),应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。 + - 调用getAddressesFromLocationName位置描述转化坐标。 + + ```ts + let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); + } else { + console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + 参考接口API说明[位置服务](../reference/apis/js-apis-geoLocationManager.md),应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。 + + 如果需要查询的位置描述可能出现多地重名的请求,可以设置GeoCodeRequest,通过设置一个经纬度范围,以高效地获取期望的准确结果。 + + +## 地理围栏开发指导 + +### 场景概述 + +地理围栏就是虚拟地理边界,当设备进入、离开某个特定地理区域时,可以接收自动通知和警告。 + +目前仅支持圆形围栏,并且依赖GNSS芯片的地理围栏功能。 + +应用场景举例:开发者可以使用地理围栏,在企业周围创建一个区域进行广告定位,在不同的地点,在移动设备上进行有针对性的促销优惠。 + +### 接口说明 + +地理围栏所使用的接口如下,详细说明参见:[位置服务](../reference/apis/js-apis-geoLocationManager.md)。 + +**表4** 地理围栏接口介绍 + +| 接口名 | 功能描述 | +| -------- | -------- | +| on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | 添加一个围栏,并订阅地理围栏事件。 | +| off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | 删除一个围栏,并取消订阅该围栏事件。 | + +### 开发步骤 + +1. 使用地理围栏功能,需要有权限ohos.permission.APPROXIMATELY_LOCATION,位置权限申请的方法和步骤见[申请位置权限开发指导](#申请位置权限开发指导)。 + +2. 导入[geoLocationManager](../reference/apis/js-apis-geoLocationManager.md)模块和[wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)模块。 + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + import wantAgent from '@ohos.wantAgent'; + ``` + +3. 创建[WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md)信息。 + + 场景一:创建拉起Ability的WantAgentInfo信息。 + + ```ts + let wantAgentObj = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。 + + // 通过WantAgentInfo的operationType设置动作类型 + let wantAgentInfo = { + wants: [ + { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: '', + entities: [], + uri: '', + parameters: {} + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] + }; + ``` + + 场景二:创建发布[公共事件](../application-models/common-event-overview.md)的WantAgentInfo信息。 + + ```ts + let wantAgentObj = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。 + + // 通过WantAgentInfo的operationType设置动作类型 + let wantAgentInfo = { + wants: [ + { + action: 'event_name', // 设置事件名 + parameters: {}, + } + ], + operationType: wantAgent.OperationType.SEND_COMMON_EVENT, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], + } + ``` + +4. 调用[getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent)方法进行创建WantAgent。 + +并且在获取到WantAgent对象之后调用地理围栏接口添加围栏。 + + ```ts + // 创建WantAgent + wantAgent.getWantAgent(wantAgentInfo, (err, data) => { + if (err) { + console.error('getWantAgent err=' + JSON.stringify(err)); + return; + } + console.info('getWantAgent success'); + wantAgentObj = data; + let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + try { + geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + }); + ``` + +5. 当设备进入或者退出该围栏时,系统会自动触发WantAgent的动作。 \ No newline at end of file diff --git a/zh-cn/application-dev/file-management/filepicker-guidelines.md b/zh-cn/application-dev/file-management/filepicker-guidelines.md index f1ca4197edd1d5690a9ce2d53e1b333321bdade0..09f4666bb813706c4cf06e2407c032b6fff6e73e 100644 --- a/zh-cn/application-dev/file-management/filepicker-guidelines.md +++ b/zh-cn/application-dev/file-management/filepicker-guidelines.md @@ -54,7 +54,7 @@ globalThis.context.startAbilityForResult( ) // FilePicker返回给startAbilityForResult的数据 -var abilityResult = { +let abilityResult = { resultCode: resultCode, want: { parameters: { diff --git a/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md index 75dd58ee4dd5edfe5da10b99f274c24f0bd8832c..b150c7aed2273e763dce9b837e9fedacfc83963e 100644 --- a/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md @@ -42,8 +42,8 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); - const path = await media.getPublicDirectory(DIR_IMAGE) + let media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_IMAGE); //myAlbum为新建文件保存路径,也是新建相册的名称 media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { if (fileAsset != undefined) { @@ -80,7 +80,7 @@ async function example() { selectionArgs: [], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let albumList = await media.getAlbums(AlbumNoArgsfetchOp); let album = albumList[0]; album.albumName = 'newAlbum'; @@ -88,7 +88,7 @@ async function example() { album.commitModify().then(function() { console.info("albumRename successfully"); }).catch(function(err){ - console.info("albumRename failed with error:"+ err); + console.info("albumRename failed with error: " + err); }); } ``` diff --git a/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md index be773ba7e8f3111b241b0e58a53729086651c9df..259774688fc5cc8031d31dd1909cb94e8a13f8c5 100644 --- a/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -37,7 +37,7 @@ Openharmony上用户数据统一由媒体库进行管理,用户数据用户数 ```ts async function example(){ const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; const dicResult = await media.getPublicDirectory(DIR_CAMERA); if (dicResult == 'Camera/') { @@ -80,11 +80,11 @@ OpenHarmony提供应用沙箱机制,增加目录可见性数据访问防线, ```ts async function copyPublic2Sandbox() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let sandboxDirPath = globalThis.context.filesDir; - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selections: fileKeyObj.DISPLAY_NAME + '= ?', selectionArgs: ['testFile.txt'], }; let fetchResult = await media.getFileAssets(fileAssetFetchOp); @@ -107,7 +107,7 @@ async function copyPublic2Sandbox() { ```ts async function copySandbox2Public() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let sandboxDirPath = globalThis.context.filesDir; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; @@ -119,26 +119,26 @@ async function copySandbox2Public() { console.info('createFile failed, message = ' + err); } try { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selections: fileKeyObj.DISPLAY_NAME + '= ?', selectionArgs: ['testFile02.txt'], }; let fetchResult = await media.getFileAssets(fileAssetFetchOp); var fileAsset = await fetchResult.getFirstObject(); } catch (err) { - console.info('file asset get failed, message = ', err) + console.info('file asset get failed, message = ' + err); } - var fdPub = await fileAsset.open('rw'); - var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); + let fdPub = await fileAsset.open('rw'); + let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); await fileio.copyFile(fdSand, fdPub); await fileio.close(fdPub); await fileio.close(fdSand); let fdPubRead = await fileAsset.open('rw'); try { - var arrayBuffer = new ArrayBuffer(4096); + let arrayBuffer = new ArrayBuffer(4096); await fileio.read(fdPubRead, arrayBuffer); - var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer)); + var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); fileAsset.close(fdPubRead); } catch (err) { console.log('read text failed, message = ', err); @@ -166,12 +166,12 @@ async function copySandbox2Public() { let mediaType = mediaLibrary.MediaType.FILE; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const path = await media.getPublicDirectory(DIR_DOCUMENTS); media.createAsset(mediaType, "testFile.text", path).then (function (asset) { - console.info("createAsset successfully:"+ JSON.stringify(asset)); + console.info("createAsset successfully:" + JSON.stringify(asset)); }).catch(function(err){ - console.info("createAsset failed with error:"+ err); + console.info("createAsset failed with error: " + err); }); } ``` @@ -191,10 +191,10 @@ async function copySandbox2Public() { ```ts async function writeOnlyPromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selections: fileKeyObj.DISPLAY_NAME + '= ?', selectionArgs: ['testFile.txt'], }; let fetchResult = await media.getFileAssets(fileAssetFetchOp); @@ -217,8 +217,8 @@ async function writeOnlyPromise() { ```ts async function readOnlyPromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { selections: fileKeyObj.DISPLAY_NAME + '= ?' , selectionArgs: ['testFile.txt'], @@ -232,7 +232,7 @@ async function readOnlyPromise() { let arrayBuffer = new ArrayBuffer(4096); await fileio.read(fd, arrayBuffer); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); - globalThis.fileContent = fileContent + globalThis.fileContent = fileContent; globalThis.fileName = fileAsset.displayName; console.info('file content: ', fileContent); await fileAsset.close(fd); diff --git a/zh-cn/application-dev/file-management/medialibrary-overview.md b/zh-cn/application-dev/file-management/medialibrary-overview.md index 674d3909fccb21c961f9c36a01eca04c099c0f89..ca8a6c4516853d181a9f27dc0f10ced9853e7e13 100644 --- a/zh-cn/application-dev/file-management/medialibrary-overview.md +++ b/zh-cn/application-dev/file-management/medialibrary-overview.md @@ -21,7 +21,7 @@ MediaLibrary提供媒体库相关能力,帮助开发者更方便地访问和 > **说明:**
> 本开发指导基于API Version 9,仅适用于Stage模型。 -应用需要先获取媒体库实例,才能访问和修改用户等个人媒体数据信息。媒体库涉及用户个人数据信息,所以应用需要向用户申请媒体库读写操作权限才能保证功能的正常运行。 +应用需要先获取媒体库实例,才能访问和修改用户等个人媒体数据信息。媒体库涉及用户个人数据信息,所以应用需要向用户申请媒体库读写操作权限才能保证功能的正常运行。在使用媒体库相关接口时如无其他注明则默认在工程代码的pages/index.ets或者其他自创的ets文件中使用 开发者在使用MediaLibrary进行功能开发前,请先掌握以下内容: @@ -42,7 +42,7 @@ MediaLibrary提供媒体库相关能力,帮助开发者更方便地访问和 import mediaLibrary from '@ohos.multimedia.mediaLibrary'; const context = getContext(this); -var media = mediaLibrary.getMediaLibrary(context); +let media = mediaLibrary.getMediaLibrary(context); ``` ## 申请媒体库功能相关权限 @@ -102,21 +102,21 @@ var media = mediaLibrary.getMediaLibrary(context); } ``` -2. 调用requestPermissionsFromUser进行权限校验,可以选择需要动态申请获取的权限。 +2. 在Ability.ts中onWindowStageCreate里调用requestPermissionsFromUser进行权限校验,可以选择需要动态申请获取的权限自行添加相应代码 ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; + import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { - var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] - var permissionRequestResult; + let list : Array = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; + let permissionRequestResult; let atManager = abilityAccessCtrl.createAtManager(); - atManager.requestPermissionsFromUser(this.context, permissions, (err,result) => { - if(err){ + atManager.requestPermissionsFromUser(this.context, list, (err, result) => { + if (err) { console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); - }else{ + } else { permissionRequestResult=result; console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); } @@ -125,4 +125,3 @@ var media = mediaLibrary.getMediaLibrary(context); } ``` - \ No newline at end of file diff --git a/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md index ef6b06acc3f1f29efefa095f87be0ab7cab41168..c64f25916fd0f07110d3d33079c9f71c9b268a2a 100644 --- a/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md @@ -33,14 +33,14 @@ selectionArgs: MediaType.IMAGE,媒体类型为图片。 ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.IMAGE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -64,13 +64,13 @@ selectionArgs:2022-8-5,具体添加时间的字符串。 ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let option = { selections: fileKeyObj.DATE_ADDED + '= ?', selectionArgs: ['2022-8-5'], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -92,15 +92,15 @@ order: FileKey.DATE_ADDED,根据文件添加日期排序;并设置排列 ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.IMAGE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], order: fileKeyObj.DATE_ADDED + " DESC", }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -124,14 +124,14 @@ selectionArgs:'myAlbum',具体相册名称。 ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.IMAGE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; let option = { selections: fileKeyObj.ALBUM_NAME + '= ?', selectionArgs: ['myAlbum'], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -186,7 +186,7 @@ async function example() { ```ts async function getCameraImagePromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let imagesFetchOp = { @@ -235,7 +235,7 @@ async function getCameraImagePromise() { ```ts async function getFirstThumbnailPromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let imagesFetchOp = { @@ -279,7 +279,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.FILE; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const path = await media.getPublicDirectory(DIR_DOCUMENTS); media.createAsset(mediaType, "testFile.text", path).then ((asset) => { console.info("createAsset successfully:"+ JSON.stringify(asset)); @@ -311,25 +311,25 @@ async function example() { ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.FILE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); let asset = await fetchFileResult.getFirstObject(); if (asset == undefined) { - console.error('asset not exist') - return + console.error('asset not exist'); + return; } //回调为空 asset.trash(true).then(() => { console.info("trash successfully"); }).catch((err) => { - console.info("trash failed with error:"+ err); + console.info("trash failed with error: " + err); }); } ``` @@ -359,19 +359,19 @@ async function example() { ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.FILE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); let asset = await fetchFileResult.getFirstObject(); if (asset == undefined) { - console.error('asset not exist') - return + console.error('asset not exist'); + return; } asset.displayName = 'newImage.jpg'; //回调为空 @@ -381,6 +381,6 @@ async function example() { return; } console.log('fileRename successful.'); - }) + }); } ``` diff --git a/zh-cn/application-dev/napi/drawing-guidelines.md b/zh-cn/application-dev/napi/drawing-guidelines.md index f89cfa322404c8a28945a91fcd58e1f8b54dbb3c..b746e15978646c5c9efed2cc24fc7ac1fac55768 100644 --- a/zh-cn/application-dev/napi/drawing-guidelines.md +++ b/zh-cn/application-dev/napi/drawing-guidelines.md @@ -118,9 +118,9 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 // 在画布上画path的形状,五角星的边框样式为pen设置,颜色填充为Brush设置 OH_Drawing_CanvasDrawPath(cCanvas, cPath); // 销毁创建的对象 - OH_Drawing_BrushDestory(cBrush); - OH_Drawing_PenDestory(cPen); - OH_Drawing_PathDestory(cPath); + OH_Drawing_BrushDestroy(cBrush); + OH_Drawing_PenDestroy(cPen); + OH_Drawing_PathDestroy(cPath); ``` 6. **获取像素数据**。使用 **drawing_bitmap.h** 的 **OH_Drawing_BitmapGetPixels** 接口获取到画布绑定bitmap实例的像素地址,该地址指向的内存包含画布刚刚绘制的像素数据。 @@ -133,9 +133,9 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 LOGI("memcpy_s failed"); } // 销毁canvas对象 - OH_Drawing_CanvasDestory(cCanvas); + OH_Drawing_CanvasDestroy(cCanvas); // 销毁bitmap对象 - OH_Drawing_BitmapDestory(cBitmap); + OH_Drawing_BitmapDestroy(cBitmap); ``` ## 文本绘制开发步骤 diff --git a/zh-cn/application-dev/quick-start/figures/02.png b/zh-cn/application-dev/quick-start/figures/02.png index 19dd76ca232282b19883dde63075c5d155e7db70..eef374a1fd63f2b1e4d72e3323e7f4c23f5705fb 100644 Binary files a/zh-cn/application-dev/quick-start/figures/02.png and b/zh-cn/application-dev/quick-start/figures/02.png differ diff --git a/zh-cn/application-dev/quick-start/figures/04.png b/zh-cn/application-dev/quick-start/figures/04.png index cf23d17c7ee8552e30a5b234c97862b51981dcf8..1190d1e5aa631b12171632d258e4c4fae32e9bba 100644 Binary files a/zh-cn/application-dev/quick-start/figures/04.png and b/zh-cn/application-dev/quick-start/figures/04.png differ diff --git a/zh-cn/application-dev/quick-start/figures/07.png b/zh-cn/application-dev/quick-start/figures/07.png index 0f34d01d824ae1780c73cade9a39fff5f4b9b84e..17f2b060d300667ff250935b6a37485843e854ce 100644 Binary files a/zh-cn/application-dev/quick-start/figures/07.png and b/zh-cn/application-dev/quick-start/figures/07.png differ diff --git a/zh-cn/application-dev/quick-start/start-with-ets-fa.md b/zh-cn/application-dev/quick-start/start-with-ets-fa.md index 6e2818d8f7a3065560aa033caeff44f41f17aeeb..611b5049b527f27f74beb2d503a2ef857f224a72 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-fa.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-fa.md @@ -223,7 +223,10 @@ .height('5%') // 跳转按钮绑定onClick事件,点击时跳转到第二页 .onClick(() => { - router.pushUrl({ url: 'pages/second' }) + router.push({ url: 'pages/second' }) + // 若为API 9工程,则可使用以下接口 + // router.pushUrl({ url: 'pages/second' }) + }) } .width('100%') diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 80afc88d666a3f08c8d10767aec684a9246cb455..6d9e94b02800d8e1d97a8ca197a85fd0e46ea9be 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -48,7 +48,7 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 需要校验的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | **返回值:** @@ -71,7 +71,7 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 try { atManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); @@ -95,7 +95,7 @@ verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | 是 | 要校验应用的身份标识。 | +| tokenID | number | 是 | 要校验应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 需要校验的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | **返回值:** @@ -116,7 +116,7 @@ verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus ```js let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 let data = atManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); console.log(`data->${JSON.stringify(data)}`); ``` @@ -137,7 +137,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被授予的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | @@ -165,7 +165,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -194,7 +194,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。| +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。| | permissionName | Permissions | 是 | 被授予的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | | callback | AsyncCallback<void> | 是 | 授予应用user grant权限。当授予权限成功时,err为undefine;否则为错误对象。 | @@ -217,7 +217,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -248,7 +248,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被撤销的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | @@ -276,7 +276,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -305,7 +305,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被撤销的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | | callback | AsyncCallback<void> | 是 | 撤销应用user grant权限。当撤销权限成功时,err为undefine;否则为错误对象。 | @@ -328,7 +328,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -359,7 +359,7 @@ getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<num | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 查询的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | **返回值:** @@ -386,7 +386,7 @@ getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<num import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 try { atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); @@ -537,7 +537,7 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<Gran | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | Permissions | 是 | 需要校验的权限名称,合法的权限名取值可在[系统权限定义列表](../../security/permission-list.md)中查询。 | **返回值:** @@ -552,7 +552,7 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<Gran import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); @@ -662,7 +662,7 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)获得。 | | permissionName | string | 是 | 需要校验的权限名称。 | **返回值:** @@ -677,7 +677,7 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); diff --git a/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index ee7e3e072ba0d069d6b9842cf0b66ec3c29f1b44..5f8f053d7e889921dc2c41349474f242788043f5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -454,6 +454,20 @@ queryCurrentBundleActiveStates(begin: number, end: number): Promise<Array< | infosBeginTime | number | 否 | BundleActiveInfo对象中第一条应用使用统计的记录时间。| | infosEndTime | number | 否 | BundleActiveInfo对象中最后一条应用使用统计的记录时间。| +### merge(deprecated) + +merge(toMerge: BundleStateInfo): void + +合并相同包名的应用使用信息。 + +**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App + +**参数**: + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| toMerge | [BundleStateInfo](#bundlestateinfo) | 是 | 相同包名的应用使用统计信息。| + ## BundleActiveState 提供应用事件的具体信息。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md index a7dbee35c1df0f916f0d707a4a08e34b215e71a7..96fdfe4a492282df8b7768476592e8320cd0286b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @@ -1,4 +1,4 @@ -# @ohos.data.fileAccess (公共文件访问与管理) +# @ohos.file.fileAccess (公共文件访问与管理) fileAccess模块是基于extension机制实现的一个对公共文件访问和操作的框架。该模块一方面对接各类文件管理服务,如媒体库、外置存储管理服务等,另一方面为系统应用提供一套统一的文件访问管理接口。其中,媒体库服务提供本地设备、分布式设备等公共文件访问服务;外置存储管理服务可以提供共享盘、U盘、SD卡等设备的公共文件访问服务。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md b/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md index bc1e98d8d6de99e35e656c77627e9cdf8e0eaab5..b55f8ba04d0c4664cf153ea178b08cc1ac5d5460 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @@ -1,4 +1,4 @@ -# @ohos.fileExtensionInfo (公共文件访问与管理属性信息) +# @ohos.file.fileExtensionInfo (公共文件访问与管理属性信息) 该模块提供公共文件访问和管理模块中RootInfo与FileInfo中部分属性值的定义。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md index 3458b6d5d211bb3d3b313a7a92dfe657b76a28ce..f067a976424b9f35415c3aea5f91727b7722dff5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -42,11 +42,286 @@ import geoLocationManager from '@ohos.geoLocationManager'; ``` +## ReverseGeoCodeRequest + +逆地理编码请求接口。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| locale | string | 是 | 是 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| latitude | number | 是 | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。取值范围为-90到90。 | +| longitude | number | 是 | 是 | 表示经度信息,正值表示东经,负值表示西经。取值范围为-180到180。 | +| maxItems | number | 是 | 是 | 指定返回位置信息的最大个数。取值范围为大于等于0,推荐该值小于10。 | + + +## GeoCodeRequest + +地理编码请求接口。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| locale | string | 是 | 是 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| description | string | 是 | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | +| maxItems | number | 是 | 是 | 表示返回位置信息的最大个数。取值范围为大于等于0,推荐该值小于10。 | +| minLatitude | number | 是 | 是 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。取值范围为-90到90。 | +| minLongitude | number | 是 | 是 | 表示最小经度信息。取值范围为-180到180。 | +| maxLatitude | number | 是 | 是 | 表示最大纬度信息。取值范围为-90到90。 | +| maxLongitude | number | 是 | 是 | 表示最大经度信息。取值范围为-180到180。 | + + +## GeoAddress + +地理编码类型。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。取值范围为-90到90。 | +| longitude | number | 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。取值范围为-180到180。 | +| locale | string | 是 | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| placeName | string | 是 | 否 | 表示地区信息。 | +| countryCode | string | 是 | 否 | 表示国家码信息。 | +| countryName | string| 是 | 否 | 表示国家信息。 | +| administrativeArea | string | 是 | 否 | 表示省份区域信息。 | +| subAdministrativeArea | string | 是 | 否 | 表示表示子区域信息。 | +| locality | string | 是 | 否 | 表示城市信息。 | +| subLocality | string | 是 | 否 | 表示子城市信息。 | +| roadName | string | 是 | 否 |表示路名信息。 | +| subRoadName | string | 是 | 否 | 表示子路名信息。 | +| premises | string| 是 | 否|表示门牌号信息。 | +| postalCode | string | 是 | 否 | 表示邮政编码信息。 | +| phoneNumber | string | 是 | 否 | 表示联系方式信息。 | +| addressUrl | string | 是 | 否 | 表示位置信息附件的网址信息。 | +| descriptions | Array<string> | 是 | 否 | 表示附加的描述信息。 | +| descriptionsSize | number | 是 | 否 | 表示附加的描述信息数量。取值范围为大于等于0,推荐该值小于10。 | +| isFromMock | Boolean | 是 | 否 | 表示地名信息是否来自于逆地理编码模拟功能。
**系统API**:此接口为系统接口。 | + + +## LocationRequest + +位置信息请求类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。取值范围见[LocationRequestPriority](#locationrequestpriority)的定义。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。取值范围见[LocationRequestScenario](#locationrequestscenario)的定义。 | +| timeInterval | number | 是 | 是 | 表示上报位置信息的时间间隔,单位是秒。取值范围为大于0。 | +| distanceInterval | number | 是 | 是 | 表示上报位置信息的距离间隔。单位是米,取值范围为大于0。 | +| maxAccuracy | number | 是 | 是 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。取值范围为大于0。 | + + +## CurrentLocationRequest + +当前位置信息请求类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。取值范围见[LocationRequestPriority](#locationrequestpriority)的定义。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。取值范围见[LocationRequestScenario](#locationrequestscenario)的定义。 | +| maxAccuracy | number | 是 | 是| 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。取值范围为大于0。 | +| timeoutMs | number | 是 | 是 | 表示超时时间,单位是毫秒,最小为1000毫秒。取值范围为大于等于1000。 | + + +## SatelliteStatusInfo + +卫星状态信息。 + +**系统能力**:SystemCapability.Location.Location.Gnss + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| satellitesNumber | number | 是 | 否 | 表示卫星个数。取值范围为大于等于0。 | +| satelliteIds | Array<number> | 是 | 否 | 表示每个卫星的ID,数组类型。取值范围为大于等于0。 | +| carrierToNoiseDensitys | Array<number> | 是 | 否 | 表示载波噪声功率谱密度比,即cn0。取值范围为大于0。 | +| altitudes | Array<number> | 是 | 否 | 表示卫星高度角信息。单位是“度”,取值范围为-90到90。 | +| azimuths | Array<number> | 是 | 否 | 表示方位角。单位是“度”,取值范围为0到360。 | +| carrierFrequencies | Array<number> | 是 | 否 | 表示载波频率。单位是Hz,取值范围为大于等于0。 | + + +## CachedGnssLocationsRequest + +请求订阅GNSS缓存位置上报功能接口的配置参数。 + +**系统能力**:SystemCapability.Location.Location.Gnss + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | 是 | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。取值范围为大于0。 | +| wakeUpCacheQueueFull | boolean | 是 | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | + + +## Geofence + +GNSS围栏的配置参数。目前只支持圆形围栏。 + +**系统能力**:SystemCapability.Location.Location.Geofence + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | 是 | 是 |表示纬度。取值范围为-90到90。 | +| longitude | number | 是 |是 | 表示经度。取值范围为-180到180。 | +| radius | number | 是 |是 | 表示圆形围栏的半径。单位是米,取值范围为大于0。 | +| expiration | number | 是 |是 | 围栏存活的时间,单位是毫秒。取值范围为大于0。 | + + +## GeofenceRequest + +请求添加GNSS围栏消息中携带的参数,包括定位优先级、定位场景和围栏信息。 + +**系统能力**:SystemCapability.Location.Location.Geofence + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示定位场景。 | +| geofence | [Geofence](#geofence)| 是 | 是 | 表示围栏信息。 | + + +## LocationCommand + +扩展命令结构体。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示定位场景。 | +| command | string | 是 | 是 | 扩展命令字符串。 | + + +## Location + +位置信息类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| latitude | number| 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。取值范围为-90到90。 | +| longitude | number| 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。取值范围为-180到180。 | +| altitude | number | 是 | 否 | 表示高度信息,单位米。 | +| accuracy | number | 是 | 否 | 表示精度信息,单位米。 | +| speed | number | 是 | 否 |表示速度信息,单位米每秒。 | +| timeStamp | number | 是 | 否 | 表示位置时间戳,UTC格式。 | +| direction | number | 是 | 否 | 表示航向信息。单位是“度”,取值范围为0到360。 | +| timeSinceBoot | number | 是 | 否 | 表示位置时间戳,开机时间格式。 | +| additions | Array<string> | 是 | 否 | 附加信息。 | +| additionSize | number | 是 | 否 | 附加信息数量。取值范围为大于等于0。 | +| isFromMock | Boolean | 是 | 否 | 表示位置信息是否来自于位置模拟功能。
**系统API**:此接口为系统接口。 | + + +## ReverseGeocodingMockInfo + +逆地理编码模拟功能的配置信息,包含一个位置信息和一个地名信息。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 是 | 表示经纬度信息。 | +| geoAddress | [GeoAddress](#geoaddress) | 是 | 是 |表示地名信息。 | + + +## LocationMockConfig + +位置模拟功能的配置参数,包含了模拟位置上报的时间间隔和模拟位置数组。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| timeInterval | number | 是 | 是 | 表示模拟位置上报的时间间隔,单位是秒。 | +| locations | Array<[Location](#location)> | 是 | 是 | 表示模拟位置数组。 | + + +## CountryCode + +国家码信息结构体,包含国家码字符串和国家码的来源信息。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 类型 | 可读|可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| country | string | 是 | 否 | 表示国家码字符串。 | +| type | [CountryCodeType](#countrycodetype) | 是 | 否 | 表示国家码信息来源。 | + + +## LocationRequestPriority + +位置请求中位置信息优先级设置。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x200 | 表示未设置优先级,表示[LocationRequestPriority](#locationrequestpriority)无效。 | +| ACCURACY | 0x201 | 表示精度优先。
定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。 | +| LOW_POWER | 0x202 | 表示低功耗优先。
低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。 | +| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到一个位置,可以将优先级设置为该字段。
快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。 | + + +## LocationRequestScenario + + 位置请求中定位场景设置。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x300 | 表示未设置场景信息。
表示[LocationRequestScenario](#locationrequestscenario)字段无效。 | +| NAVIGATION | 0x301 | 表示导航场景。
适用于在户外定位设备实时位置的场景,如车载、步行导航。
在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务
此场景默认以最小1秒间隔上报定位结果。 | +| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。
适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。
此场景默认以最小1秒间隔上报定位结果。 | +| CAR_HAILING | 0x303 | 表示打车场景。
适用于用户出行打车时定位当前位置的场景,如网约车类应用。
此场景默认以最小1秒间隔上报定位结果。 | +| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。
适用于不需要定位用户精确位置的使用场景,如新闻资讯、网购、点餐类应用,做推荐、推送时定位用户大致位置即可。
此场景默认以最小1秒间隔上报定位结果。 | +| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | + + +## LocationPrivacyType + +定位服务隐私协议类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| OTHERS | 0 | 其他场景。预留字段。 | +| STARTUP | 1 | 开机向导场景下的隐私协议。在开机时弹出协议,提醒用户阅读并选择是否授权。 | +| CORE_LOCATION | 2 | 开启网络定位时弹出的隐私协议。 | + + +## CountryCodeType + +国家码来源类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | 从全球化模块的语言配置信息中获取到的国家码。 | +| COUNTRY_CODE_FROM_SIM | 2 | 从SIM卡中获取到的国家码。 | +| COUNTRY_CODE_FROM_LOCATION | 3 | 基于用户的位置信息,通过逆地理编码查询到的国家码。 | +| COUNTRY_CODE_FROM_NETWORK | 4 | 从蜂窝网络注册信息中获取到的国家码。 | + + ## geoLocationManager.on('locationChange') on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void -开启位置变化订阅,并发起定位请求。定位结果按照[LocationRequest](#locationrequest)的属性进行上报, +开启位置变化订阅,并发起定位请求。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -74,8 +349,8 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - var locationChange = (location) => { + let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; try { @@ -118,8 +393,8 @@ off(type: 'locationChange', callback?: Callback<Location>): void ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - var locationChange = (location) => { + let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; try { @@ -158,7 +433,7 @@ on(type: 'locationEnabledChange', callback: Callback<boolean>): void ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var locationEnabledChange = (state) => { + let locationEnabledChange = (state) => { console.log('locationEnabledChange: ' + JSON.stringify(state)); } try { @@ -196,7 +471,7 @@ off(type: 'locationEnabledChange', callback?: Callback<boolean>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var locationEnabledChange = (state) => { + let locationEnabledChange = (state) => { console.log('locationEnabledChange: state: ' + JSON.stringify(state)); } try { @@ -240,10 +515,10 @@ on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callb ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var cachedLocationsCb = (locations) => { + let cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); } - var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; try { geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); } catch (err) { @@ -283,10 +558,10 @@ off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location& ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var cachedLocationsCb = (locations) => { + let cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); } - var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; try { geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); geoLocationManager.off('cachedGnssLocationsChange'); @@ -326,7 +601,7 @@ on(type: 'satelliteStatusChange', callback: Callback<SatelliteStatusInfo>) ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var gnssStatusCb = (satelliteStatusInfo) => { + let gnssStatusCb = (satelliteStatusInfo) => { console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -369,7 +644,7 @@ off(type: 'satelliteStatusChange', callback?: Callback<SatelliteStatusInfo> ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var gnssStatusCb = (satelliteStatusInfo) => { + let gnssStatusCb = (satelliteStatusInfo) => { console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } try { @@ -412,7 +687,7 @@ on(type: 'nmeaMessage', callback: Callback<string>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var nmeaCb = (str) => { + let nmeaCb = (str) => { console.log('nmeaMessage: ' + JSON.stringify(str)); } @@ -455,7 +730,7 @@ off(type: 'nmeaMessage', callback?: Callback<string>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var nmeaCb = (str) => { + let nmeaCb = (str) => { console.log('nmeaMessage: ' + JSON.stringify(str)); } @@ -484,7 +759,7 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssFenceStatusChange”,表示订阅围栏事件上报。 | | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | - | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | + | want | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **错误码**: @@ -516,7 +791,7 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; try { geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); } catch (err) { @@ -542,7 +817,7 @@ off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): v | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssFenceStatusChange”,表示订阅围栏事件上报。 | | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | - | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | + | want | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **错误码**: @@ -574,7 +849,7 @@ off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): v }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; try { geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj); @@ -615,7 +890,7 @@ on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var callback = (code) => { + let callback = (code) => { console.log('countryCodeChange: ' + JSON.stringify(code)); } @@ -656,7 +931,7 @@ off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var callback = (code) => { + let callback = (code) => { console.log('countryCodeChange: ' + JSON.stringify(code)); } @@ -701,8 +976,8 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; - var locationChange = (err, location) => { + let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + let locationChange = (err, location) => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -748,7 +1023,7 @@ getCurrentLocation(callback: AsyncCallback<Location>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var locationChange = (err, location) => { + let locationChange = (err, location) => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -794,113 +1069,41 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> | -------- | ---------------------------------------- | |3301000 | Location service is unavailable. | |3301100 | The location switch is off. | -|3301200 | Failed to obtain the geographical location. | - -**示例** - - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; - try { - geoLocationManager.getCurrentLocation(requestInfo).then((result) => { - console.log('current location: ' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, getCurrentLocation: error=' + JSON.stringify(error)); - }); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - -## geoLocationManager.getLastLocation - -getLastLocation(): Location - -获取上一次位置。 - -**需要权限**:ohos.permission.APPROXIMATELY_LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -**返回值**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | Location | [Location](#location) | NA | 位置信息。 | - -**错误码**: - -以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 - -| 错误码ID | 错误信息 | -| -------- | ---------------------------------------- | -|3301000 | Location service is unavailable. | -|3301100 | The location switch is off. | -|3301200 |Failed to obtain the geographical location. | - -**示例** - - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - try { - var location = geoLocationManager.getLastLocation(); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - -## geoLocationManager.isLocationEnabled - -isLocationEnabled(): boolean - -判断位置服务是否已经使能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**返回值**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | boolean | boolean | NA | 位置服务是否已经使能。 | - -**错误码**: - -以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 - -| 错误码ID | 错误信息 | -| -------- | ---------------------------------------- | -|3301000 | Location service is unavailable. | +|3301200 | Failed to obtain the geographical location. | **示例** ```ts import geoLocationManager from '@ohos.geoLocationManager'; + let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; try { - var locationEnabled = geoLocationManager.isLocationEnabled(); + geoLocationManager.getCurrentLocation(requestInfo).then((result) => { + console.log('current location: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCurrentLocation: error=' + JSON.stringify(error)); + }); } catch (err) { console.error("errCode:" + err.code + ",errMessage:" + err.message); } ``` -## geoLocationManager.requestEnableLocation +## geoLocationManager.getLastLocation -requestEnableLocation(callback: AsyncCallback<boolean>): void +getLastLocation(): Location -请求使能位置服务,使用callback回调异步返回结果。 +获取上一次位置。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION **系统能力**:SystemCapability.Location.Location.Core -**参数**: +**返回值**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | 是 | callback返回true表示用户同意使能位置服务,false表示用户不同意使能位置服务。 | + | Location | [Location](#location) | NA | 位置信息。 | **错误码**: @@ -909,34 +1112,26 @@ requestEnableLocation(callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | |3301000 | Location service is unavailable. | -|3301700 | No response to the request. | +|3301100 | The location switch is off. | +|3301200 |Failed to obtain the geographical location. | **示例** ```ts import geoLocationManager from '@ohos.geoLocationManager'; try { - geoLocationManager.requestEnableLocation((err, data) => { - if (err) { - console.log('requestEnableLocation: err=' + JSON.stringify(err)); - } - if (data) { - console.log('requestEnableLocation: data=' + JSON.stringify(data)); - } - }); + let location = geoLocationManager.getLastLocation(); } catch (err) { console.error("errCode:" + err.code + ",errMessage:" + err.message); } ``` -## geoLocationManager.requestEnableLocation - -requestEnableLocation(): Promise<boolean> +## geoLocationManager.isLocationEnabled -请求使能位置服务,使用Promise方式异步返回结果。 +isLocationEnabled(): boolean -**需要权限**:ohos.permission.APPROXIMATELY_LOCATION +判断位置服务是否已经使能。 **系统能力**:SystemCapability.Location.Location.Core @@ -944,7 +1139,7 @@ requestEnableLocation(): Promise<boolean> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | Promise<boolean> | boolean | NA | 返回true表示用户同意使能位置服务,false表示用户不同意使能位置服务。 | + | boolean | boolean | NA | 位置服务是否已经使能。 | **错误码**: @@ -953,19 +1148,13 @@ requestEnableLocation(): Promise<boolean> | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | |3301000 | Location service is unavailable. | -|3301700 | No response to the request. | **示例** ```ts import geoLocationManager from '@ohos.geoLocationManager'; try { - geoLocationManager.requestEnableLocation().then((result) => { - console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, requestEnableLocation: error=' + JSON.stringify(error)); - }); + let locationEnabled = geoLocationManager.isLocationEnabled(); } catch (err) { console.error("errCode:" + err.code + ",errMessage:" + err.message); } @@ -1117,7 +1306,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; try { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -1166,7 +1355,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<Ge ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; try { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -1208,7 +1397,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; try { geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -1257,7 +1446,7 @@ getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAd ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; try { geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -1297,7 +1486,7 @@ isGeocoderAvailable(): boolean; ```ts import geoLocationManager from '@ohos.geoLocationManager'; try { - var isAvailable = geoLocationManager.isGeocoderAvailable(); + let isAvailable = geoLocationManager.isGeocoderAvailable(); } catch (err) { console.error("errCode:" + err.code + ",errMessage:" + err.message); } @@ -1502,7 +1691,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<void>): void ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + let requestInfo = {'scenario': 0x301, 'command': "command_1"}; try { geoLocationManager.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1547,7 +1736,7 @@ sendCommand(command: LocationCommand): Promise<void>; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + let requestInfo = {'scenario': 0x301, 'command': "command_1"}; try { geoLocationManager.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand success'); @@ -1712,6 +1901,8 @@ setMockedLocations(config: LocationMockConfig): void; 设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 +该接口需要在调用[geoLocationManager.enableLocationMock](#geolocationmanagerenablelocationmock)之后才能调用。 + **系统能力**:SystemCapability.Location.Location.Core **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -1735,15 +1926,16 @@ setMockedLocations(config: LocationMockConfig): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var locations = [ + let locations = [ {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} ]; - var config = {"timeInterval": 5, "locations": locations}; + let config = {"timeInterval": 5, "locations": locations}; try { + geoLocationManager.enableLocationMock(); geoLocationManager.setMockedLocations(config); } catch (err) { console.error("errCode:" + err.code + ",errMessage:" + err.message); @@ -1817,6 +2009,8 @@ setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): v 设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 +该接口需要在调用[geoLocationManager.enableReverseGeocodingMock](#geolocationmanagerenablereversegeocodingmock)之后才能调用。 + **系统能力**:SystemCapability.Location.Location.Core **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -1839,7 +2033,7 @@ setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): v ```ts import geoLocationManager from '@ohos.geoLocationManager'; - var mockInfos = [ + let mockInfos = [ {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, @@ -1847,6 +2041,7 @@ setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): v {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, ]; try { + geoLocationManager.enableReverseGeocodingMock(); geoLocationManager.setReverseGeocodingMockInfo(mockInfos); } catch (err) { console.error("errCode:" + err.code + ",errMessage:" + err.message); @@ -1889,7 +2084,7 @@ isLocationPrivacyConfirmed(type: LocationPrivacyType): boolean; ```ts import geoLocationManager from '@ohos.geoLocationManager'; try { - var isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1); + let isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1); } catch (err) { console.error("errCode:" + err.code + ",errMessage:" + err.message); } @@ -1933,276 +2128,3 @@ setLocationPrivacyConfirmStatus(type: LocationPrivacyType, isConfirmed: boolean) console.error("errCode:" + err.code + ",errMessage:" + err.message); } ``` - - -## LocationRequestPriority - -位置请求中位置信息优先级设置。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x200 | 表示未设置优先级。 | -| ACCURACY | 0x201 | 表示精度优先。 | -| LOW_POWER | 0x202 | 表示低功耗优先。 | -| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | - - -## LocationRequestScenario - - 位置请求中定位场景设置。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x300 | 表示未设置场景信息。 | -| NAVIGATION | 0x301 | 表示导航场景。 | -| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | -| CAR_HAILING | 0x303 | 表示打车场景。 | -| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | -| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | - - -## ReverseGeoCodeRequest - -逆地理编码请求接口。 - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| locale | string | 是 | 是 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| latitude | number | 是 | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude | number | 是 | 是 | 表示经度信息,正值表示东经,负值表示西经。 | -| maxItems | number | 是 | 是 | 指定返回位置信息的最大个数。 | - - -## GeoCodeRequest - -地理编码请求接口。 - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| locale | string | 是 | 是 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| description | string | 是 | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | -| maxItems | number | 是 | 是 | 表示返回位置信息的最大个数。 | -| minLatitude | number | 是 | 是 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | -| minLongitude | number | 是 | 是 | 表示最小经度信息。 | -| maxLatitude | number | 是 | 是 | 表示最大纬度信息。 | -| maxLongitude | number | 是 | 是 | 表示最大经度信息。 | - - -## GeoAddress - -地理编码类型。 - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| latitude | number | 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude | number | 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。 | -| locale | string | 是 | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| placeName | string | 是 | 否 | 表示地区信息。 | -| countryCode | string | 是 | 否 | 表示国家码信息。 | -| countryName | string| 是 | 否 | 表示国家信息。 | -| administrativeArea | string | 是 | 否 | 表示省份区域信息。 | -| subAdministrativeArea | string | 是 | 否 | 表示表示子区域信息。 | -| locality | string | 是 | 否 | 表示城市信息。 | -| subLocality | string | 是 | 否 | 表示子城市信息。 | -| roadName | string | 是 | 否 |表示路名信息。 | -| subRoadName | string | 是 | 否 | 表示子路名信息。 | -| premises | string| 是 | 否|表示门牌号信息。 | -| postalCode | string | 是 | 否 | 表示邮政编码信息。 | -| phoneNumber | string | 是 | 否 | 表示联系方式信息。 | -| addressUrl | string | 是 | 否 | 表示位置信息附件的网址信息。 | -| descriptions | Array<string> | 是 | 否 | 表示附加的描述信息。 | -| descriptionsSize | number | 是 | 否 | 表示附加的描述信息数量。 | -| isFromMock | Boolean | 是 | 否 | 表示地名信息是否来自于逆地理编码模拟功能。 | - - -## LocationRequest - -位置信息请求类型。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。 | -| timeInterval | number | 是 | 是 | 表示上报位置信息的时间间隔。 | -| distanceInterval | number | 是 | 是 | 表示上报位置信息的距离间隔。 | -| maxAccuracy | number | 是 | 是 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | - - -## CurrentLocationRequest - -当前位置信息请求类型。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。 | -| maxAccuracy | number | 是 | 是| 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | -| timeoutMs | number | 是 | 是 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | - - -## SatelliteStatusInfo - -卫星状态信息。 - -**系统能力**:SystemCapability.Location.Location.Gnss - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| satellitesNumber | number | 是 | 否 | 表示卫星个数。 | -| satelliteIds | Array<number> | 是 | 否 | 表示每个卫星的ID,数组类型。 | -| carrierToNoiseDensitys | Array<number> | 是 | 否 | 表示载波噪声功率谱密度比,即cn0。 | -| altitudes | Array<number> | 是 | 否 | 表示高程信息。 | -| azimuths | Array<number> | 是 | 否 | 表示方位角。 | -| carrierFrequencies | Array<number> | 是 | 否 | 表示载波频率。 | - - -## CachedGnssLocationsRequest - -请求订阅GNSS缓存位置上报功能接口的配置参数。 - -**系统能力**:SystemCapability.Location.Location.Gnss - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | 是 | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | -| wakeUpCacheQueueFull | boolean | 是 | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | - - -## Geofence - -GNSS围栏的配置参数。目前只支持圆形围栏。 - -**系统能力**:SystemCapability.Location.Location.Geofence - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| latitude | number | 是 | 是 |表示纬度。 | -| longitude | number | 是 |是 | 表示经度。 | -| radius | number | 是 |是 | 表示圆形围栏的半径。 | -| expiration | number | 是 |是 | 围栏存活的时间,单位是毫秒。 | - - -## GeofenceRequest - -请求添加GNSS围栏消息中携带的参数,包括定位优先级、定位场景和围栏信息。 - -**系统能力**:SystemCapability.Location.Location.Geofence - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示定位场景。 | -| geofence | [Geofence](#geofence)| 是 | 是 | 表示围栏信息。 | - - -## LocationPrivacyType - -定位服务隐私协议类型。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| OTHERS | 0 | 其他场景。 | -| STARTUP | 1 | 开机向导场景下的隐私协议。 | -| CORE_LOCATION | 2 | 开启网络定位时弹出的隐私协议。 | - - -## LocationCommand - -扩展命令结构体。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示定位场景。 | -| command | string | 是 | 是 | 扩展命令字符串。 | - - -## Location - -位置信息类型。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| latitude | number| 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude | number| 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。 | -| altitude | number | 是 | 否 | 表示高度信息,单位米。 | -| accuracy | number | 是 | 否 | 表示精度信息,单位米。 | -| speed | number | 是 | 否 |表示速度信息,单位米每秒。 | -| timeStamp | number | 是 | 否 | 表示位置时间戳,UTC格式。 | -| direction | number | 是 | 否 | 表示航向信息。 | -| timeSinceBoot | number | 是 | 否 | 表示位置时间戳,开机时间格式。 | -| additions | Array<string> | 是 | 否 | 附加信息。 | -| additionSize | number | 是 | 否 | 附加信息数量。 | -| isFromMock | Boolean | 是 | 否 | 表示位置信息是否来自于位置模拟功能。 | - - -## ReverseGeocodingMockInfo - -逆地理编码模拟功能的配置信息,包含一个位置信息和一个地名信息。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 是 | 表示经纬度信息。 | -| geoAddress | [GeoAddress](#geoaddress) | 是 | 是 |表示地名信息。 | - - -## LocationMockConfig - -位置模拟功能的配置参数,包含了模拟位置上报的时间间隔和模拟位置数组。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| timeInterval | number | 是 | 是 | 表示模拟位置上报的时间间隔,单位是秒。 | -| locations | Array<Location> | 是 | 是 | 表示模拟位置数组。 | - - -## CountryCode - -国家码信息结构体,包含国家码字符串和国家码的来源信息。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 类型 | 可读|可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| country | string | 是 | 否 | 表示国家码字符串。 | -| type | [CountryCodeType](#countrycodetype) | 是 | 否 | 表示国家码信息来源。 | - - -## CountryCodeType - -国家码来源类型。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| COUNTRY_CODE_FROM_LOCALE | 1 | 从全球化模块的语言配置信息中获取到的国家码。 | -| COUNTRY_CODE_FROM_SIM | 2 | 从SIM卡中获取到的国家码。 | -| COUNTRY_CODE_FROM_LOCATION | 3 | 基于用户的位置信息,通过逆地理编码查询到的国家码。 | -| COUNTRY_CODE_FROM_NETWORK | 4 | 从蜂窝网络注册信息中获取到的国家码。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md index 7681678b46c71cfb9d900163f7ef3067598fec78..16a018d2ce0dfd446255a4eeb6df6a104a02b3c1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md @@ -41,11 +41,11 @@ API9及之后的版本,需要申请ohos.permission.APPROXIMATELY_LOCATION或 import geolocation from '@ohos.geolocation'; ``` -## geolocation.on('locationChange')(deprecated) +## geolocation.on('locationChange')(deprecated) on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void -开启位置变化订阅,并发起定位请求。定位结果按照[LocationRequest](#locationrequest)的属性进行上报, +开启位置变化订阅,并发起定位请求。 > **说明:**
> 从API version 9开始废弃,建议使用[geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange)替代。 @@ -59,8 +59,8 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“locationChange”,表示位置变化。 | - | request | [LocationRequest](#locationrequest) | 是 | 设置位置请求参数。 | - | callback | Callback<[Location](#location)> | 是 | 接收位置变化状态变化监听。 | + | request | [LocationRequest](#locationrequestdeprecated) | 是 | 设置位置请求参数。 | + | callback | Callback<[Location](#locationdeprecated)> | 是 | 接收位置变化状态变化监听。 | @@ -68,15 +68,15 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat ```ts import geolocation from '@ohos.geolocation'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - var locationChange = (location) => { + let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; geolocation.on('locationChange', requestInfo, locationChange); ``` -## geolocation.off('locationChange')(deprecated) +## geolocation.off('locationChange')(deprecated) off(type: 'locationChange', callback?: Callback<Location>): void @@ -94,15 +94,15 @@ off(type: 'locationChange', callback?: Callback<Location>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“locationChange”,表示位置变化。 | - | callback | Callback<[Location](#location)> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | + | callback | Callback<[Location](#locationdeprecated)> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - var locationChange = (location) => { + let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; geolocation.on('locationChange', requestInfo, locationChange); @@ -110,7 +110,7 @@ off(type: 'locationChange', callback?: Callback<Location>): void ``` -## geolocation.on('locationServiceState')(deprecated) +## geolocation.on('locationServiceState')(deprecated) on(type: 'locationServiceState', callback: Callback<boolean>): void @@ -135,14 +135,14 @@ on(type: 'locationServiceState', callback: Callback<boolean>): void ```ts import geolocation from '@ohos.geolocation'; - var locationServiceState = (state) => { + let locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); ``` -## geolocation.off('locationServiceState')(deprecated) +## geolocation.off('locationServiceState')(deprecated) off(type: 'locationServiceState', callback?: Callback<boolean>): void; @@ -167,7 +167,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>): void; ```ts import geolocation from '@ohos.geolocation'; - var locationServiceState = (state) => { + let locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); @@ -175,7 +175,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>): void; ``` -## geolocation.on('cachedGnssLocationsReporting')(deprecated) +## geolocation.on('cachedGnssLocationsReporting')(deprecated) on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; @@ -194,23 +194,23 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“cachedGnssLocationsReporting”,表示GNSS缓存定位结果上报。 | - | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | 是 | GNSS缓存功能配置参数 | - | callback | Callback<Array<[Location](#location)>> | 是 | 接收GNSS缓存位置上报。 | + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequestdeprecated) | 是 | GNSS缓存功能配置参数 | + | callback | Callback<Array<[Location](#locationdeprecated)>> | 是 | 接收GNSS缓存位置上报。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var cachedLocationsCb = (locations) => { + let cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } - var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); ``` -## geolocation.off('cachedGnssLocationsReporting')(deprecated) +## geolocation.off('cachedGnssLocationsReporting')(deprecated) off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; @@ -229,23 +229,23 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“cachedGnssLocationsReporting”,表示GNSS缓存定位结果上报。 | - | callback | Callback<Array<[Location](#location)>> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | + | callback | Callback<Array<[Location](#locationdeprecated)>> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var cachedLocationsCb = (locations) => { + let cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } - var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); geolocation.off('cachedGnssLocationsReporting'); ``` -## geolocation.on('gnssStatusChange')(deprecated) +## geolocation.on('gnssStatusChange')(deprecated) on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; @@ -264,21 +264,21 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 | - | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 是 | 接收GNSS卫星状态信息上报。 | + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfodeprecated)> | 是 | 接收GNSS卫星状态信息上报。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var gnssStatusCb = (satelliteStatusInfo) => { + let gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); ``` -## geolocation.off('gnssStatusChange')(deprecated) +## geolocation.off('gnssStatusChange')(deprecated) off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; @@ -297,13 +297,13 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 | - | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfodeprecated)> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var gnssStatusCb = (satelliteStatusInfo) => { + let gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); @@ -311,7 +311,7 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): v ``` -## geolocation.on('nmeaMessageChange')(deprecated) +## geolocation.on('nmeaMessageChange')(deprecated) on(type: 'nmeaMessageChange', callback: Callback<string>): void; @@ -337,14 +337,14 @@ on(type: 'nmeaMessageChange', callback: Callback<string>): void; ```ts import geolocation from '@ohos.geolocation'; - var nmeaCb = (str) => { + let nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb ); ``` -## geolocation.off('nmeaMessageChange')(deprecated) +## geolocation.off('nmeaMessageChange')(deprecated) off(type: 'nmeaMessageChange', callback?: Callback<string>): void; @@ -370,7 +370,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>): void; ```ts import geolocation from '@ohos.geolocation'; - var nmeaCb = (str) => { + let nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb); @@ -378,7 +378,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>): void; ``` -## geolocation.on('fenceStatusChange')(deprecated) +## geolocation.on('fenceStatusChange')(deprecated) on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; @@ -397,9 +397,8 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 | - | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | - | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | - + | request | [GeofenceRequest](#geofencerequestdeprecated) | 是 | 围栏的配置参数。 | + | want | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **示例** @@ -421,13 +420,13 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); }); ``` -## geolocation.off('fenceStatusChange')(deprecated) +## geolocation.off('fenceStatusChange')(deprecated) off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; @@ -446,8 +445,8 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 | - | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | - | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | + | request | [GeofenceRequest](#geofencerequestdeprecated) | 是 | 围栏的配置参数。 | + | want | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **示例** @@ -469,14 +468,14 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); geolocation.off('fenceStatusChange', requestInfo, wantAgentObj); }); ``` -## geolocation.getCurrentLocation(deprecated) +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void @@ -493,15 +492,15 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | 是 | 设置位置请求参数。 | - | callback | AsyncCallback<[Location](#location)> | 是 | 用来接收位置信息的回调。 | + | request | [CurrentLocationRequest](#currentlocationrequestdeprecated) | 是 | 设置位置请求参数。 | + | callback | AsyncCallback<[Location](#locationdeprecated)> | 是 | 用来接收位置信息的回调。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; - var locationChange = (err, location) => { + let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + let locationChange = (err, location) => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -513,7 +512,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L ``` -## geolocation.getCurrentLocation(deprecated) +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(callback: AsyncCallback<Location>): void @@ -531,13 +530,13 @@ getCurrentLocation(callback: AsyncCallback<Location>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Location](#location)> | 是 | 用来接收位置信息的回调。 | + | callback | AsyncCallback<[Location](#locationdeprecated)> | 是 | 用来接收位置信息的回调。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var locationChange = (err, location) => { + let locationChange = (err, location) => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -549,7 +548,7 @@ getCurrentLocation(callback: AsyncCallback<Location>): void ``` -## geolocation.getCurrentLocation(deprecated) +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> @@ -566,27 +565,27 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | 否 | 设置位置请求参数。 | + | request | [CurrentLocationRequest](#currentlocationrequestdeprecated) | 否 | 设置位置请求参数。 | **返回值**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | Promise<[Location](#location)> |[Location](#location)|NA| 返回位置信息。 | + | Promise<[Location](#locationdeprecated)> |[Location](#locationdeprecated)|NA| 返回位置信息。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); }); ``` -## geolocation.getLastLocation(deprecated) +## geolocation.getLastLocation(deprecated) getLastLocation(callback: AsyncCallback<Location>): void @@ -603,7 +602,7 @@ getLastLocation(callback: AsyncCallback<Location>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Location](#location)> | 是 | 用来接收上次位置的回调。 | + | callback | AsyncCallback<[Location](#locationdeprecated)> | 是 | 用来接收上次位置的回调。 | **示例** @@ -621,7 +620,7 @@ getLastLocation(callback: AsyncCallback<Location>): void ``` -## geolocation.getLastLocation(deprecated) +## geolocation.getLastLocation(deprecated) getLastLocation(): Promise<Location> @@ -638,7 +637,7 @@ getLastLocation(): Promise<Location> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | Promise<[Location](#location)> | [Location](#location)|NA|返回上次位置信息。 | + | Promise<[Location](#locationdeprecated)> | [Location](#locationdeprecated)|NA|返回上次位置信息。 | **示例** @@ -651,7 +650,7 @@ getLastLocation(): Promise<Location> ``` -## geolocation.isLocationEnabled(deprecated) +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(callback: AsyncCallback<boolean>): void @@ -685,7 +684,7 @@ isLocationEnabled(callback: AsyncCallback<boolean>): void ``` -## geolocation.isLocationEnabled(deprecated) +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(): Promise<boolean> @@ -714,14 +713,14 @@ isLocationEnabled(): Promise<boolean> ``` -## geolocation.requestEnableLocation(deprecated) +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(callback: AsyncCallback<boolean>): void 请求打开位置服务,使用callback回调异步返回结果。 > **说明:**
-> 从API version 9开始废弃,建议使用[geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation)替代。 +> 从API version 9开始废弃,建议由应用本身弹框请求用户跳转到settings开启位置开关,并且在弹框上写清楚会在什么场景下使用位置信息。 **需要权限**:ohos.permission.LOCATION @@ -748,14 +747,14 @@ requestEnableLocation(callback: AsyncCallback<boolean>): void ``` -## geolocation.requestEnableLocation(deprecated) +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(): Promise<boolean> 请求打开位置服务,使用Promise方式异步返回结果。 > **说明:**
-> 从API version 9开始废弃,建议使用[geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation-1)替代。 +> 从API version 9开始废弃,建议由应用本身弹框请求用户跳转到settings开启位置开关,并且在弹框上写清楚会在什么场景下使用位置信息。 **需要权限**:ohos.permission.LOCATION @@ -777,7 +776,7 @@ requestEnableLocation(): Promise<boolean> ``` -## geolocation.isGeoServiceAvailable(deprecated) +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(callback: AsyncCallback<boolean>): void @@ -811,7 +810,7 @@ isGeoServiceAvailable(callback: AsyncCallback<boolean>): void ``` -## geolocation.isGeoServiceAvailable(deprecated) +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(): Promise<boolean> @@ -840,7 +839,7 @@ isGeoServiceAvailable(): Promise<boolean> ``` -## geolocation.getAddressesFromLocation(deprecated) +## geolocation.getAddressesFromLocation(deprecated) getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void @@ -857,14 +856,14 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 设置逆地理编码请求的相关参数。 | - | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | 是 | 设置接收逆地理编码请求的回调参数。 | + | request | [ReverseGeoCodeRequest](#reversegeocoderequestdeprecated) | 是 | 设置逆地理编码请求的相关参数。 | + | callback | AsyncCallback<Array<[GeoAddress](#geoaddressdeprecated)>> | 是 | 设置接收逆地理编码请求的回调参数。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); @@ -876,7 +875,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback ``` -## geolocation.getAddressesFromLocation(deprecated) +## geolocation.getAddressesFromLocation(deprecated) getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; @@ -893,26 +892,26 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<Ge | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 设置逆地理编码请求的相关参数。 | + | request | [ReverseGeoCodeRequest](#reversegeocoderequestdeprecated) | 是 | 设置逆地理编码请求的相关参数。 | **返回值**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|返回地理描述信息。 | + | Promise<Array<[GeoAddress](#geoaddressdeprecated)>> | Array<[GeoAddress](#geoaddressdeprecated)>|NA|返回地理描述信息。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); }); ``` -## geolocation.getAddressesFromLocationName(deprecated) +## geolocation.getAddressesFromLocationName(deprecated) getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void @@ -929,14 +928,14 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | request | [GeoCodeRequest](#geocoderequest) | 是 | 设置地理编码请求的相关参数。 | - | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | 是 | 设置接收地理编码请求的回调参数。 | + | request | [GeoCodeRequest](#geocoderequestdeprecated) | 是 | 设置地理编码请求的相关参数。 | + | callback | AsyncCallback<Array<[GeoAddress](#geoaddressdeprecated)>> | 是 | 设置接收地理编码请求的回调参数。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); @@ -948,7 +947,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< ``` -## geolocation.getAddressesFromLocationName(deprecated) +## geolocation.getAddressesFromLocationName(deprecated) getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> @@ -965,26 +964,26 @@ getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAd | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | request | [GeoCodeRequest](#geocoderequest) | 是 | 设置地理编码请求的相关参数。 | + | request | [GeoCodeRequest](#geocoderequestdeprecated) | 是 | 设置地理编码请求的相关参数。 | **返回值**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|设置接收地理编码请求的回调参数。 | + | Promise<Array<[GeoAddress](#geoaddressdeprecated)>> | Array<[GeoAddress](#geoaddressdeprecated)>|NA|设置接收地理编码请求的回调参数。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); }); ``` -## geolocation.getCachedGnssLocationsSize(deprecated) +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; @@ -1019,7 +1018,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; ``` -## geolocation.getCachedGnssLocationsSize(deprecated) +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(): Promise<number>; @@ -1049,7 +1048,7 @@ getCachedGnssLocationsSize(): Promise<number>; ``` -## geolocation.flushCachedGnssLocations(deprecated) +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; @@ -1084,7 +1083,7 @@ flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; ``` -## geolocation.flushCachedGnssLocations(deprecated) +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(): Promise<boolean>; @@ -1114,7 +1113,7 @@ flushCachedGnssLocations(): Promise<boolean>; ``` -## geolocation.sendCommand(deprecated) +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; @@ -1132,14 +1131,14 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | command | [LocationCommand](#locationcommand) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | + | command | [LocationCommand](#locationcommanddeprecated) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | | callback | AsyncCallback<boolean> | 是 | 用来接收命令发送的结果。 | **示例** ```ts import geolocation from '@ohos.geolocation'; - var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + let requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { console.log('sendCommand: err=' + JSON.stringify(err)); @@ -1151,7 +1150,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): v ``` -## geolocation.sendCommand(deprecated) +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand): Promise<boolean>; @@ -1169,7 +1168,7 @@ sendCommand(command: LocationCommand): Promise<boolean>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | command | [LocationCommand](#locationcommand) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | + | command | [LocationCommand](#locationcommanddeprecated) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | **返回值**: @@ -1181,76 +1180,14 @@ sendCommand(command: LocationCommand): Promise<boolean>; ```ts import geolocation from '@ohos.geolocation'; - var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + let requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); }); ``` -## LocationRequestPriority(deprecated) - -位置请求中位置信息优先级设置。 - -> **说明:**
-> 从API version 9开始废弃,建议使用[geoLocationManager.LocationRequestPriority](js-apis-geoLocationManager.md#locationrequestpriority)替代。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x200 | 表示未设置优先级。 | -| ACCURACY | 0x201 | 表示精度优先。 | -| LOW_POWER | 0x202 | 表示低功耗优先。 | -| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | - - -## LocationRequestScenario(deprecated) - - 位置请求中定位场景设置。 - -> **说明:**
-> 从API version 9开始废弃,建议使用[geoLocationManager.LocationRequestScenario](js-apis-geoLocationManager.md#locationrequestscenario)替代。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x300 | 表示未设置场景信息。 | -| NAVIGATION | 0x301 | 表示导航场景。 | -| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | -| CAR_HAILING | 0x303 | 表示打车场景。 | -| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | -| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | - - -## GeoLocationErrorCode(deprecated) - -位置服务中的错误码信息。 - -> **说明:**
-> 从API version 9开始废弃。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| INPUT_PARAMS_ERROR7+ | 101 | 表示输入参数错误。 | -| REVERSE_GEOCODE_ERROR7+ | 102 | 表示逆地理编码接口调用失败。 | -| GEOCODE_ERROR7+ | 103 | 表示地理编码接口调用失败。 | -| LOCATOR_ERROR7+ | 104 | 表示定位失败。 | -| LOCATION_SWITCH_ERROR7+ | 105 | 表示定位开关。 | -| LAST_KNOWN_LOCATION_ERROR7+ | 106 | 表示获取上次位置失败。 | -| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | 表示单次定位,没有在指定时间内返回位置。 | - - -## ReverseGeoCodeRequest(deprecated) +## ReverseGeoCodeRequest(deprecated) 逆地理编码请求接口。 @@ -1264,12 +1201,12 @@ sendCommand(command: LocationCommand): Promise<boolean>; | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | locale | string | 是 | 是 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| latitude | number | 是 | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude | number | 是 | 是 | 表示经度信息,正值表示东经,负值表示西经。 | -| maxItems | number | 是 | 是 | 指定返回位置信息的最大个数。 | +| latitude | number | 是 | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。取值范围为-90到90。 | +| longitude | number | 是 | 是 | 表示经度信息,正值表示东经,负值表示西经。取值范围为-180到180。 | +| maxItems | number | 是 | 是 | 指定返回位置信息的最大个数。取值范围为大于等于0,推荐该值小于10。 | -## GeoCodeRequest(deprecated) +## GeoCodeRequest(deprecated) 地理编码请求接口。 @@ -1284,14 +1221,14 @@ sendCommand(command: LocationCommand): Promise<boolean>; | -------- | -------- | -------- | -------- | -------- | | locale | string | 是 | 是 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | | description | string | 是 | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | -| maxItems | number | 是 | 是 | 表示返回位置信息的最大个数。 | -| minLatitude | number | 是 | 是 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | -| minLongitude | number | 是 | 是 | 表示最小经度信息。 | -| maxLatitude | number | 是 | 是 | 表示最大纬度信息。 | -| maxLongitude | number | 是 | 是 | 表示最大经度信息。 | +| maxItems | number | 是 | 是 | 表示返回位置信息的最大个数。取值范围为大于等于0,推荐该值小于10。 | +| minLatitude | number | 是 | 是 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。取值范围为-90到90。 | +| minLongitude | number | 是 | 是 | 表示最小经度信息。取值范围为-180到180。 | +| maxLatitude | number | 是 | 是 | 表示最大纬度信息。取值范围为-90到90。 | +| maxLongitude | number | 是 | 是 | 表示最大经度信息。取值范围为-180到180。 | -## GeoAddress(deprecated) +## GeoAddress(deprecated) 地理编码类型。 @@ -1304,8 +1241,8 @@ sendCommand(command: LocationCommand): Promise<boolean>; | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| latitude7+ | number | 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude7+ | number | 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。 | +| latitude7+ | number | 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。取值范围为-90到90。 | +| longitude7+ | number | 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。取值范围为-180到180。 | | locale7+ | string | 是 | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | | placeName7+ | string | 是 | 否 | 表示地区信息。 | | countryCode7+ | string | 是 | 否 | 表示国家码信息。 | @@ -1321,10 +1258,10 @@ sendCommand(command: LocationCommand): Promise<boolean>; | phoneNumber7+ | string | 是 | 否| 表示联系方式信息。 | | addressUrl7+ | string | 是 | 否 | 表示位置信息附件的网址信息。 | | descriptions7+ | Array<string> | 是 | 否 | 表示附加的描述信息。 | -| descriptionsSize7+ | number | 是 | 否 | 表示附加的描述信息数量。 | +| descriptionsSize7+ | number | 是 | 否 | 表示附加的描述信息数量。取值范围为大于等于0,推荐该值小于10。 | -## LocationRequest(deprecated) +## LocationRequest(deprecated) 位置信息请求类型。 @@ -1337,14 +1274,14 @@ sendCommand(command: LocationCommand): Promise<boolean>; | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。 | -| timeInterval | number | 是 | 是 | 表示上报位置信息的时间间隔。 | -| distanceInterval | number | 是 | 是 | 表示上报位置信息的距离间隔。 | -| maxAccuracy | number | 是 | 是 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | +| priority | [LocationRequestPriority](#locationrequestprioritydeprecated) | 是 | 是 | 表示优先级信息。取值范围见[LocationRequestPriority](#locationrequestprioritydeprecated)的定义。 | +| scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | 是 | 是 | 表示场景信息。取值范围见[LocationRequestScenario](#locationrequestscenariodeprecated)的定义。 | +| timeInterval | number | 是 | 是 | 表示上报位置信息的时间间隔,单位是秒。取值范围为大于0。 | +| distanceInterval | number | 是 | 是 | 表示上报位置信息的距离间隔。单位是米,取值范围为大于0。 | +| maxAccuracy | number | 是 | 是 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。取值范围为大于0。 | -## CurrentLocationRequest(deprecated) +## CurrentLocationRequest(deprecated) 当前位置信息请求类型。 @@ -1357,13 +1294,13 @@ sendCommand(command: LocationCommand): Promise<boolean>; | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。 | -| maxAccuracy | number | 是 | 是| 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | -| timeoutMs | number | 是 | 是 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | +| priority | [LocationRequestPriority](#locationrequestprioritydeprecated) | 是 | 是 | 表示优先级信息。取值范围见[LocationRequestPriority](#locationrequestprioritydeprecated)的定义。 | +| scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | 是 | 是 | 表示场景信息。取值范围见[LocationRequestScenario](#locationrequestscenariodeprecated)的定义。 | +| maxAccuracy | number | 是 | 是| 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。取值范围为大于0。 | +| timeoutMs | number | 是 | 是 | 表示超时时间,单位是毫秒,最小为1000毫秒。取值范围为大于等于1000。 | -## SatelliteStatusInfo(deprecated) +## SatelliteStatusInfo(deprecated) 卫星状态信息。 @@ -1377,15 +1314,15 @@ sendCommand(command: LocationCommand): Promise<boolean>; | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| satellitesNumber | number | 是 | 否 | 表示卫星个数。 | -| satelliteIds | Array<number> | 是 | 否 | 表示每个卫星的ID,数组类型。 | -| carrierToNoiseDensitys | Array<number> | 是 | 否 | 表示载波噪声功率谱密度比,即cn0。 | -| altitudes | Array<number> | 是 | 否 | 表示高程信息。 | -| azimuths | Array<number> | 是 | 否 | 表示方位角。 | -| carrierFrequencies | Array<number> | 是 | 否 | 表示载波频率。 | +| satellitesNumber | number | 是 | 否 | 表示卫星个数。取值范围为大于等于0。 | +| satelliteIds | Array<number> | 是 | 否 | 表示每个卫星的ID,数组类型。取值范围为大于等于0。 | +| carrierToNoiseDensitys | Array<number> | 是 | 否 | 表示载波噪声功率谱密度比,即cn0。取值范围为大于0。 | +| altitudes | Array<number> | 是 | 否 | 表示卫星高度角信息。单位是“度”,取值范围为-90到90。 | +| azimuths | Array<number> | 是 | 否 | 表示方位角。单位是“度”,取值范围为0到360。 | +| carrierFrequencies | Array<number> | 是 | 否 | 表示载波频率。单位是Hz,取值范围为大于等于0。 | -## CachedGnssLocationsRequest(deprecated) +## CachedGnssLocationsRequest(deprecated) 请求订阅GNSS缓存位置上报功能接口的配置参数。 @@ -1399,11 +1336,11 @@ sendCommand(command: LocationCommand): Promise<boolean>; | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | 是 | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | +| reportingPeriodSec | number | 是 | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。取值范围为大于0。 | | wakeUpCacheQueueFull | boolean | 是 | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | -## Geofence(deprecated) +## Geofence(deprecated) GNSS围栏的配置参数。目前只支持圆形围栏。 @@ -1417,13 +1354,13 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| latitude | number | 是 | 是 | 表示纬度。 | -| longitude | number | 是 | 是 | 表示经度。 | -| radius | number | 是 | 是 | 表示圆形围栏的半径。 | -| expiration | number | 是 | 是 | 围栏存活的时间,单位是毫秒。 | +| latitude | number | 是 | 是 |表示纬度。取值范围为-90到90。 | +| longitude | number | 是 |是 | 表示经度。取值范围为-180到180。 | +| radius | number | 是 |是 | 表示圆形围栏的半径。单位是米,取值范围为大于0。 | +| expiration | number | 是 |是 | 围栏存活的时间,单位是毫秒。取值范围为大于0。 | -## GeofenceRequest(deprecated) +## GeofenceRequest(deprecated) 请求添加GNSS围栏消息中携带的参数,包括定位优先级、定位场景和围栏信息。 @@ -1437,31 +1374,12 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示位置信息优先级。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示定位场景。 | -| geofence | [Geofence](#geofence)| 是 | 是 | 表示围栏信息。 | - - -## LocationPrivacyType(deprecated) - -定位服务隐私协议类型。 - -> **说明:**
-> 从API version 8开始支持。 -> 从API version 9开始废弃,建议使用[geoLocationManager.LocationPrivacyType](js-apis-geoLocationManager.md#locationprivacytype)替代。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| OTHERS | 0 | 其他场景。 | -| STARTUP | 1 | 开机向导场景下的隐私协议。 | -| CORE_LOCATION | 2 | 开启网络定位时弹出的隐私协议。 | +| priority | [LocationRequestPriority](#locationrequestprioritydeprecated) | 是 | 是 | 表示位置信息优先级。 | +| scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | 是 | 是 | 表示定位场景。 | +| geofence | [Geofence](#geofencedeprecated)| 是 | 是 | 表示围栏信息。 | -## LocationCommand(deprecated) +## LocationCommand(deprecated) 扩展命令结构体。 @@ -1475,11 +1393,11 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示定位场景。 | +| scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | 是 | 是 | 表示定位场景。 | | command | string | 是 | 是 | 扩展命令字符串。 | -## Location(deprecated) +## Location(deprecated) 位置信息类型。 @@ -1492,13 +1410,94 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| latitude7+ | number | 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude7+ | number | 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。 | +| latitude7+ | number | 是 | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。取值范围为-90到90。 | +| longitude7+ | number | 是 | 否 | 表示经度信息,正值表示东经,负值表是西经。取值范围为-180到180。 | | altitude7+ | number | 是 | 否 | 表示高度信息,单位米。 | | accuracy7+ | number | 是 | 否 | 表示精度信息,单位米。 | | speed7+ | number | 是 | 否 | 表示速度信息,单位米每秒。 | | timeStamp7+ | number | 是 | 否 | 表示位置时间戳,UTC格式。 | -| direction7+ | number | 是 | 否 | 表示航向信息。 | +| direction7+ | number | 是 | 否 | 表示航向信息。单位是“度”,取值范围为0到360。 | | timeSinceBoot7+ | number | 是 | 否 | 表示位置时间戳,开机时间格式。 | | additions7+ | Array<string> | 是 | 否 | 附加信息。 | -| additionSize7+ | number | 是 | 否 | 附加信息数量。 | \ No newline at end of file +| additionSize7+ | number | 是 | 否 | 附加信息数量。取值范围为大于等于0。 | + + +## LocationPrivacyType(deprecated) + +定位服务隐私协议类型。 + +> **说明:**
+> 从API version 8开始支持。 +> 从API version 9开始废弃,建议使用[geoLocationManager.LocationPrivacyType](js-apis-geoLocationManager.md#locationprivacytype)替代。 + +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| OTHERS | 0 | 其他场景。预留字段。 | +| STARTUP | 1 | 开机向导场景下的隐私协议。在开机时弹出协议,提醒用户阅读并选择是否授权。 | +| CORE_LOCATION | 2 | 开启网络定位时弹出的隐私协议。 | + + +## LocationRequestPriority(deprecated) + +位置请求中位置信息优先级设置。 + +> **说明:**
+> 从API version 9开始废弃,建议使用[geoLocationManager.LocationRequestPriority](js-apis-geoLocationManager.md#locationrequestpriority)替代。 + +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x200 | 表示未设置优先级,表示[LocationRequestPriority](#locationrequestprioritydeprecated)无效。 | +| ACCURACY | 0x201 | 表示精度优先。
定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。 | +| LOW_POWER | 0x202 | 表示低功耗优先。
低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。 | +| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到一个位置,可以将优先级设置为该字段。
快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。 | + + +## LocationRequestScenario(deprecated) + + 位置请求中定位场景设置。 + +> **说明:**
+> 从API version 9开始废弃,建议使用[geoLocationManager.LocationRequestScenario](js-apis-geoLocationManager.md#locationrequestscenario)替代。 + +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x300 | 表示未设置场景信息。
表示[LocationRequestScenario](#locationrequestscenariodeprecated)字段无效。 | +| NAVIGATION | 0x301 | 表示导航场景。
适用于在户外定位设备实时位置的场景,如车载、步行导航。
在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务
此场景默认以最小1秒间隔上报定位结果。 | +| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。
适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。
此场景默认以最小1秒间隔上报定位结果。 | +| CAR_HAILING | 0x303 | 表示打车场景。
适用于用户出行打车时定位当前位置的场景,如网约车类应用。
此场景默认以最小1秒间隔上报定位结果。 | +| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。
适用于不需要定位用户精确位置的使用场景,如新闻资讯、网购、点餐类应用,做推荐、推送时定位用户大致位置即可。
此场景默认以最小1秒间隔上报定位结果。 | +| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | + + +## GeoLocationErrorCode(deprecated) + +位置服务中的错误码信息。 + +> **说明:**
+> 从API version 9开始废弃。 + +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| INPUT_PARAMS_ERROR7+ | 101 | 表示输入参数错误。 | +| REVERSE_GEOCODE_ERROR7+ | 102 | 表示逆地理编码接口调用失败。 | +| GEOCODE_ERROR7+ | 103 | 表示地理编码接口调用失败。 | +| LOCATOR_ERROR7+ | 104 | 表示定位失败。 | +| LOCATION_SWITCH_ERROR7+ | 105 | 表示定位开关。 | +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | 表示获取上次位置失败。 | +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | 表示单次定位,没有在指定时间内返回位置。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 0740e38c53b57a3aa2dbadb5dedfa487422b511f..3705107c58c21a7ce66a4c79fc333a63aa9b1f8d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -61,7 +61,7 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapp", abilityName: "MyAbility" }; @@ -126,12 +126,12 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var options = { + let options = { windowMode: 0 }; @@ -200,11 +200,11 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapp", abilityName: "MyAbility" }; - var options = { + let options = { windowMode: 0, }; @@ -267,7 +267,7 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -333,12 +333,12 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var options = { + let options = { windowMode: 0, }; @@ -409,11 +409,11 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityRes **示例:** ```ts -var want = { +let want = { bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; -var options = { +let options = { windowMode: 0, }; @@ -481,12 +481,12 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { @@ -555,13 +555,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -636,13 +636,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -697,7 +697,7 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" @@ -753,7 +753,7 @@ startServiceExtensionAbility(want: Want): Promise\; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" @@ -813,12 +813,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -873,16 +873,16 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId) - .then((data) => { + .then(() => { // 执行正常业务 console.log('startServiceExtensionAbilityWithAccount succeed'); }) @@ -929,7 +929,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" @@ -984,7 +984,7 @@ stopServiceExtensionAbility(want: Want): Promise\; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" @@ -992,7 +992,7 @@ stopServiceExtensionAbility(want: Want): Promise\; try { this.context.stopServiceExtensionAbility(want) - .then((data) => { + .then(() => { // 执行正常业务 console.log('stopServiceExtensionAbility succeed'); }) @@ -1043,12 +1043,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -1102,16 +1102,16 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId) - .then((data) => { + .then(() => { // 执行正常业务 console.log('stopServiceExtensionAbilityWithAccount succeed'); }) @@ -1250,13 +1250,13 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapplication", abilityName: "EntryAbility" } - var resultCode = 100; + let resultCode = 100; // 返回给接口调用方AbilityResult信息 - var abilityResult = { + let abilityResult = { want, resultCode } @@ -1314,20 +1314,20 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapplication", abilityName: "EntryAbility" } - var resultCode = 100; + let resultCode = 100; // 返回给接口调用方AbilityResult信息 - var abilityResult = { + let abilityResult = { want, resultCode } try { this.context.terminateSelfWithResult(abilityResult) - .then((data) => { + .then(() => { // 执行正常业务 console.log('terminateSelfWithResult succeed'); }) @@ -1378,12 +1378,12 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" }; - var options = { + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, @@ -1395,7 +1395,7 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbility(want, options); } catch (paramError) { @@ -1444,13 +1444,13 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "ServiceExtensionAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, @@ -1462,7 +1462,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); } catch (paramError) { @@ -1505,11 +1505,11 @@ disconnectServiceExtensionAbility(connection: number): Promise\; ```ts // connection为connectServiceExtensionAbility中的返回值 - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection) - .then((data) => { + .then(() => { // 执行正常业务 console.log('disconnectServiceExtensionAbility succeed'); }) @@ -1553,7 +1553,7 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\ { @@ -1623,10 +1623,10 @@ startAbilityByCall(want: Want): Promise<Caller>; 后台启动: ```ts - var caller = undefined; + let caller = undefined; // 后台启动Ability,不配置parameters - var wantBackground = { + let wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", abilityName: "EntryAbility", @@ -1654,10 +1654,10 @@ startAbilityByCall(want: Want): Promise<Caller>; 前台启动: ```ts - var caller = undefined; + let caller = undefined; // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true - var wantForeground = { + let wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", abilityName: "EntryAbility", @@ -1731,12 +1731,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { @@ -1804,13 +1804,13 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -1879,19 +1879,19 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; try { this.context.startAbilityWithAccount(want, accountId, options) - .then((data) => { + .then(() => { // 执行正常业务 console.log('startAbilityWithAccount succeed'); }) @@ -1994,9 +1994,9 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; ```ts import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -2047,9 +2047,9 @@ setMissionIcon(icon: image.PixelMap): Promise\; **示例:** ```ts - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -2094,7 +2094,7 @@ restoreWindowStage(localStorage: LocalStorage) : void; **示例:** ```ts - var storage = new LocalStorage(); + let storage = new LocalStorage(); this.context.restoreWindowStage(storage); ``` @@ -2122,6 +2122,6 @@ isTerminating(): boolean; **示例:** ```ts - var isTerminating = this.context.isTerminating(); + let isTerminating = this.context.isTerminating(); console.log('ability state :' + isTerminating); ``` 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 7ae6d88fe7ae60eb5e4c879e7ca13acd721d6ac8..11b66612820b56dc2127007225d553f5214f3dd6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -202,7 +202,7 @@ on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange' | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | | callback | Callback<void> | 是 | 回调返回空 | **示例:** @@ -224,7 +224,7 @@ off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | | callback | Callback<void> | 否 | 回调返回空 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-stationary.md b/zh-cn/application-dev/reference/apis/js-apis-stationary.md index 12a01a763208c6ca85ae69da19903345cee1d73d..acb4c1767efade3f622be4c76d074bc653319e17 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-stationary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-stationary.md @@ -5,6 +5,8 @@ > **说明:** > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 本模块不支持x86模拟器。 ## 导入模块 diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-location.md b/zh-cn/application-dev/reference/apis/js-apis-system-location.md index a0eef27362da1a659eafcb6f4211dfc6c116a73c..b2a31156f422a66047093aa514a5ef9e249aa88f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-location.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-location.md @@ -1,5 +1,7 @@ # @system.geolocation (地理位置) +本模块仅提供GNSS定位、网络定位等基本功能。 + > **说明:** > - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 从API Version 9开始,该接口不再维护,推荐使用新接口[geoLocationManager](js-apis-geoLocationManager.md)。 @@ -7,7 +9,6 @@ ## 导入模块 - ``` import geolocation from '@system.geolocation'; ``` @@ -18,7 +19,7 @@ import geolocation from '@system.geolocation'; ohos.permission.LOCATION -## geolocation.getLocation(deprecated) +## geolocation.getLocation(deprecated) getLocation(Object): void @@ -55,7 +56,7 @@ fail返回错误代码: | -------- | -------- | | 601 | 获取定位权限失败,失败原因:用户拒绝。 | | 602 | 权限未声明。 | -| 800 | 超时,失败原因:网络状况不佳或GPS不可用。 | +| 800 | 超时,失败原因:网络状况不佳或GNSS不可用。 | | 801 | 系统位置开关未打开。 | | 802 | 该次调用结果未返回前接口又被重新调用,该次调用失败返回错误码。 | @@ -77,14 +78,14 @@ export default { ``` -## geolocation.getLocationType(deprecated) +## geolocation.getLocationType(deprecated) getLocationType(Object): void 获取当前设备支持的定位类型。 > **说明:**
-> 从API version 9开始废弃。 +> 从API version 9开始废弃。位置服务子系统仅支持gnss和network两种定位类型,后续不再提供接口查询支持的定位类型。 **系统能力:** SystemCapability.Location.Location.Lite @@ -120,7 +121,7 @@ export default { ``` -## geolocation.subscribe(deprecated) +## geolocation.subscribe(deprecated) subscribe(Object): void @@ -175,7 +176,7 @@ export default { ``` -## geolocation.unsubscribe(deprecated) +## geolocation.unsubscribe(deprecated) unsubscribe(): void @@ -197,14 +198,14 @@ export default { ``` -## geolocation.getSupportedCoordTypes(deprecated) +## geolocation.getSupportedCoordTypes(deprecated) getSupportedCoordTypes(): Array<string> 获取设备支持的坐标系类型。 > **说明:**
-> 从API version 9开始废弃。 +> 从API version 9开始废弃。位置服务子系统仅支持wgs84坐标系,后续不再提供接口查询支持的坐标系类型。 **系统能力:** SystemCapability.Location.Location.Lite diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-time.md b/zh-cn/application-dev/reference/apis/js-apis-system-time.md index 28a590c48593577a910a36b04f981f236a903efc..bb21d6f388879054e23fd445a8a0c5510b7bbe97 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-time.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-time.md @@ -29,6 +29,14 @@ setTime(time : number, callback : AsyncCallback<void>) : void | time | number | 是 | 目标时间戳(ms)。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **示例:** ```js @@ -69,6 +77,14 @@ setTime(time : number) : Promise<void> | ------------------- | ------------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **示例:** ```js @@ -104,6 +120,14 @@ getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void | isNano | boolean | 是 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | | callback | AsyncCallback<number> | 是 | 回调函数,返回自Unix纪元以来经过的时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -138,6 +162,14 @@ getCurrentTime(callback: AsyncCallback<number>): void | -------- | ----------- | ---- | ---------------------------------- | | callback | AsyncCallback<number> | 是 | 回调函数,返回自Unix纪元以来经过的时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -178,6 +210,14 @@ getCurrentTime(isNano?: boolean): Promise<number> | --------------------- | --------------------------- | | Promise<number> | Promise对象,返回自Unix纪元以来经过的时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -211,6 +251,14 @@ getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void | isNano | boolean | 是 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,但不包括度睡眠时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -245,6 +293,14 @@ getRealActiveTime(callback: AsyncCallback<number>): void | -------- | -------------- | ---- | --------------------- | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,但不包括度睡眠时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -285,6 +341,14 @@ getRealActiveTime(isNano?: boolean): Promise<number> | -------------- | -------------------------------- | | Promise<number> | Promise对象,返回自系统启动以来经过的时间,但不包括深度睡眠时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -318,6 +382,14 @@ getRealTime(isNano: boolean, callback: AsyncCallback<number>): void | isNano | boolean | 是 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,包括深度睡眠时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -352,6 +424,14 @@ getRealTime(callback: AsyncCallback<number>): void | -------- | --------- | ---- | --------------------------- | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,包括深度睡眠时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -392,6 +472,14 @@ getRealTime(isNano?: boolean): Promise<number> | --------------------- | ------------------------------- | | Promise<number> | Promise对象,返回自系统启动以来经过的时间,包括深度睡眠时间。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -423,6 +511,14 @@ setDate(date: Date, callback: AsyncCallback<void>): void | date | Date | 是 | 目标日期。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **示例:** ```js @@ -462,6 +558,14 @@ setDate(date: Date): Promise<void> | ------------------- | -------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **示例:** ```js @@ -495,6 +599,14 @@ getDate(callback: AsyncCallback<Date>): void | -------- | -------------- | ---- | --------------------- | | callback | AsyncCallback<Date> | 是 | 回调函数,返回当前系统日期。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -529,6 +641,14 @@ getDate(): Promise<Date> | ------------------- | ----------------------------------------- | | Promise<Date> | Promise对象,返回当前系统日期。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -560,6 +680,14 @@ setTimezone(timezone: string, callback: AsyncCallback<void>): void | timezone | string | 是 | 系统时区。 具体可见[支持的系统时区](#支持的系统时区) 。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **示例:** ```js @@ -598,6 +726,14 @@ setTimezone(timezone: string): Promise<void> | ------------------- | -------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **示例:** ```js @@ -630,6 +766,14 @@ getTimezone(callback: AsyncCallback<string>): void | -------- | --------- | ---- | ------------------------ | | callback | AsyncCallback<string> | 是 | 回调函数,返回系统时区。具体可见[支持的系统时区](#支持的系统时区) 。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js @@ -664,6 +808,14 @@ getTimezone(): Promise<string> | --------------------- | ------------------------------------- | | Promise<string> | Promise对象,返回系统时区。具体可见[支持的系统时区](#支持的系统时区) 。 | +**错误码:** + +以下错误码的详细介绍请参见[时间时区错误码](../errorcodes/errorcode-time.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md index bf2320e1b06b9ed1cccdf1cead5af2d752b0df6f..a984437a476941facb1cffb82fa17e9b625899f9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @@ -37,6 +37,7 @@ getUserFileMgr(context: Context): UserFileManager **示例:** ```ts +//此处获取的userFileManager实例mgr为全局对象,后续使用到mgr的地方默认为使用此处获取的对象,如未添加此段代码报mgr未定义的错误请自行添加 const context = getContext(this); let mgr = userFileManager.getUserFileMgr(context); ``` @@ -126,7 +127,7 @@ async function example() { predicates: predicates }; try { - var fetchResult = await mgr.getPhotoAssets(fetchOptions); + let fetchResult = await mgr.getPhotoAssets(fetchOptions); if (fetchResult != undefined) { console.info('fetchResult success'); let fileAsset = await fetchResult.getFirstObject(); @@ -306,7 +307,7 @@ async function example() { getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>>; -获取相册,使用callback方式返回结果。 +获取相册,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -409,7 +410,7 @@ getPrivateAlbum(type: PrivateAlbumType): Promise<FetchResult<PrivateAlbum& async function example() { console.info('getPrivateAlbumDemo'); try { - var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); let trashAlbum = await fetchResult.getFirstObject(); console.info('first album.albumName = ' + trashAlbum.albumName); } catch (err) { @@ -434,7 +435,7 @@ getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | | options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | -| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回相册检索结果 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回音频检索结果 | **示例:** @@ -484,7 +485,7 @@ getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise 返回相册检索结果 | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise 返回音频检索结果 | **示例:** 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 5432507250239156f799559c35988404572eec02..0a5e19b9a21fb16731ed6c4df5f08d1494a9c751 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 @@ -2,7 +2,7 @@ 提供具有网页显示能力的Web组件。 -> **说明:** +> **说明:** > > - 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > - 示例效果请以真机运行为准,当前IDE预览器不支持。 @@ -1181,6 +1181,54 @@ struct WebComponent { } ``` +### allowWindowOpenMethod9+ + +allowWindowOpenMethod(flag: boolean) + +设置网页是否可以通过JavaScript自动打开新窗口。 + +该属性为true时,可通过JavaScript自动打开新窗口。该属性为false时,用户行为仍可通过JavaScript自动打开新窗口,但非用户行为不能通过JavaScript自动打开新窗口。此处的用户行为是指用户在5秒内请求打开新窗口(window.open)。 + +该属性仅在[javaScriptAccess](#javascriptaccess)开启时生效。 + +该属性在[multiWindowAccess](#multiwindowaccess9)开启时打开新窗口,关闭时打开本地窗口。 + +该属性的默认值与系统属性persist.web.allowWindowOpenMethod.enabled 保持一致,如果未设置系统属性则默认值为false。 + +检查系统配置项persist.web.allowWindowOpenMethod.enabled 是否开启。 + +通过`hdc shell param get persist.web.allowWindowOpenMethod.enabled` 查看,若配置项为0或不存在, +可通过命令`hdc shell param set persist.web.allowWindowOpenMethod.enabled 1` 开启配置。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| ------ | ------- | ---- | ----- | ------------------ | +| flag | boolean | 是 | 默认值与系统参数关联,当系统参数persist.web.allowWindowOpenMethod.enabled为true时,默认值为true, 否则为false | 网页是否可以通过JavaScript自动打开窗口。 | + +**示例:** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State access: boolean = true + @State multiWindow: boolean = true + @State flag: boolean = true + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .javaScriptAccess(this.access) + .multiWindowAccess(this.multiWindow) + .allowWindowOpenMethod(this.flag) + } + } + } + ``` + ## 事件 不支持通用事件。 @@ -1271,7 +1319,7 @@ onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResu @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1332,7 +1380,7 @@ onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1392,7 +1440,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1452,7 +1500,7 @@ onConsole(callback: (event?: { message: ConsoleMessage }) => boolean) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1489,7 +1537,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1526,7 +1574,7 @@ onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResou @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1570,7 +1618,7 @@ onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: W @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1621,7 +1669,7 @@ onPageBegin(callback: (event?: { url: string }) => void) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1654,7 +1702,7 @@ onPageEnd(callback: (event?: { url: string }) => void) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1686,7 +1734,7 @@ onProgressChange(callback: (event?: { newProgress: number }) => void) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1718,7 +1766,7 @@ onTitleReceive(callback: (event?: { title: string }) => void) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1751,7 +1799,7 @@ onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1783,7 +1831,7 @@ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => voi @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'chrome://crash/', controller: this.controller }) @@ -1871,7 +1919,7 @@ onResourceLoad(callback: (event: {url: string}) => void) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1904,7 +1952,7 @@ onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1942,7 +1990,7 @@ onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => b @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2050,7 +2098,7 @@ onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, r struct WebComponent { controller: WebController = new WebController() httpAuth: boolean = false - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2111,7 +2159,7 @@ onSslErrorEventReceive(callback: (event: { handler: SslErrorHandler, error: SslE @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2754,7 +2802,7 @@ getLineNumber(): number 获取ConsoleMessage的行数。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | -------------------- | @@ -2766,7 +2814,7 @@ getMessage(): string 获取ConsoleMessage的日志信息。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ---------------------- | @@ -2778,7 +2826,7 @@ getMessageLevel(): MessageLevel 获取ConsoleMessage的信息级别。 -**返回值:** +**返回值:** | 类型 | 说明 | | --------------------------------- | ---------------------- | @@ -2790,7 +2838,7 @@ getSourceId(): string 获取网页源文件路径和名字。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ------------- | @@ -2860,7 +2908,7 @@ getErrorCode(): number 获取加载资源的错误码。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ----------- | @@ -2872,7 +2920,7 @@ getErrorInfo(): string 获取加载资源的错误信息。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ------------ | @@ -2888,7 +2936,7 @@ getResponseHeader() : Array\ 获取资源请求头信息。 -**返回值:** +**返回值:** | 类型 | 说明 | | -------------------------- | ---------- | @@ -2900,7 +2948,7 @@ getRequestUrl(): string 获取资源请求的URL信息。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ------------- | @@ -2912,7 +2960,7 @@ isMainFrame(): boolean 判断资源请求是否为主frame。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------- | ---------------- | @@ -2924,7 +2972,7 @@ isRedirect(): boolean 判断资源请求是否被服务端重定向。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------- | ---------------- | @@ -2936,7 +2984,7 @@ isRequestGesture(): boolean 获取资源请求是否与手势(如点击)相关联。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------- | -------------------- | @@ -2962,7 +3010,7 @@ getReasonMessage(): string 获取资源响应的状态码描述。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ------------- | @@ -2974,7 +3022,7 @@ getResponseCode(): number 获取资源响应的状态码。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ----------- | @@ -2986,7 +3034,7 @@ getResponseData(): string 获取资源响应数据。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | --------- | @@ -2998,7 +3046,7 @@ getResponseEncoding(): string 获取资源响应的编码。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ---------- | @@ -3010,7 +3058,7 @@ getResponseHeader() : Array\ 获取资源响应头。 -**返回值:** +**返回值:** | 类型 | 说明 | | -------------------------- | -------- | @@ -3022,7 +3070,7 @@ getResponseMimeType(): string 获取资源响应的媒体(MIME)类型。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ------------------ | @@ -3138,7 +3186,7 @@ getTitle(): string 获取文件选择器标题。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------ | ---------- | @@ -3150,7 +3198,7 @@ getMode(): FileSelectorMode 获取文件选择器的模式。 -**返回值:** +**返回值:** | 类型 | 说明 | | ---------------------------------------- | ----------- | @@ -3162,7 +3210,7 @@ getAcceptType(): Array\ 获取文件过滤类型。 -**返回值:** +**返回值:** | 类型 | 说明 | | --------------- | --------- | @@ -3174,7 +3222,7 @@ isCapture(): boolean 获取是否调用多媒体能力。 -**返回值:** +**返回值:** | 类型 | 说明 | | ------- | ------------ | @@ -3581,7 +3629,7 @@ requestFocus() @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('requestFocus') @@ -3616,7 +3664,7 @@ accessBackward(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('accessBackward') @@ -3652,7 +3700,7 @@ accessForward(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('accessForward') @@ -3695,7 +3743,7 @@ accessStep(step: number): boolean struct WebComponent { controller: WebController = new WebController() @State steps: number = 2 - + build() { Column() { Button('accessStep') @@ -3725,7 +3773,7 @@ backward(): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('backward') @@ -3754,7 +3802,7 @@ forward(): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('forward') @@ -3788,7 +3836,7 @@ backOrForward(step: number): void struct WebComponent { controller: WebController = new WebController() @State step: number = -2 - + build() { Column() { Button('backOrForward') @@ -3824,7 +3872,7 @@ deleteJavaScriptRegister(name: string) struct WebComponent { controller: WebController = new WebController() @State name: string = 'Object' - + build() { Column() { Button('deleteJavaScriptRegister') @@ -3841,7 +3889,7 @@ deleteJavaScriptRegister(name: string) getHitTest(): HitTestType -获取当前被点击区域的元素类型。 +获取当前被点击区域的元素类型。 从API version 9开始不再维护,建议使用[getHitTest9+](../apis/js-apis-webview.md#gethittest)代替。 @@ -3859,7 +3907,7 @@ getHitTest(): HitTestType @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getHitTest') @@ -3892,7 +3940,7 @@ getHitTestValue(): HitTestValue @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getHitTestValue') @@ -3926,7 +3974,7 @@ getWebId(): number @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getWebId') @@ -3959,7 +4007,7 @@ getTitle(): string @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getTitle') @@ -3992,7 +4040,7 @@ getPageHeight(): number @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getPageHeight') @@ -4025,7 +4073,7 @@ getDefaultUserAgent(): string @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getDefaultUserAgent') @@ -4069,7 +4117,7 @@ baseUrl为空时,通过”data“协议加载指定的一段字符串。 @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('loadData') @@ -4113,7 +4161,7 @@ loadUrl(options: { url: string | Resource, headers?: Array\ }) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('loadUrl') @@ -4142,7 +4190,7 @@ onActive(): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('onActive') @@ -4171,7 +4219,7 @@ onInactive(): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('onInactive') @@ -4206,7 +4254,7 @@ zoom(factor: number): void struct WebComponent { controller: WebController = new WebController() @State factor: number = 1 - + build() { Column() { Button('zoom') @@ -4238,7 +4286,7 @@ zoomIn(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('zoomIn') @@ -4271,7 +4319,7 @@ zoomOut(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('zoomOut') @@ -4301,7 +4349,7 @@ refresh() @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('refresh') @@ -4379,7 +4427,7 @@ registerJavaScriptProxy(options: { object: object, name: string, methodList: Arr } - + ``` ### runJavaScript(deprecated) @@ -4459,7 +4507,7 @@ stop() @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('stop') @@ -4488,7 +4536,7 @@ clearHistory(): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('clearHistory') @@ -4575,7 +4623,7 @@ getCookieManager(): WebCookie @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getCookieManager') @@ -4915,7 +4963,7 @@ setCookie(url: string, value: string): boolean | url | string | 是 | - | 要设置的cookie所属的url。 | | value | string | 是 | - | cookie的值。 | -**返回值:** +**返回值:** | 类型 | 说明 | | ------- | ------------- | @@ -4929,7 +4977,7 @@ setCookie(url: string, value: string): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('setCookie') @@ -4962,7 +5010,7 @@ saveCookieSync(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('saveCookieSync') @@ -5002,7 +5050,7 @@ getCookie(url: string): string @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getCookie') @@ -5043,7 +5091,7 @@ setCookie(url: string, value: string): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('setCookie') @@ -5077,7 +5125,7 @@ saveCookieAsync(): Promise\ @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('saveCookieAsync') @@ -5116,7 +5164,7 @@ saveCookieAsync(callback: AsyncCallback\): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('saveCookieAsync') @@ -5151,7 +5199,7 @@ isCookieAllowed(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('isCookieAllowed') @@ -5185,7 +5233,7 @@ putAcceptCookieEnabled(accept: boolean): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('putAcceptCookieEnabled') @@ -5218,7 +5266,7 @@ isThirdCookieAllowed(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('isThirdPartyCookieAllowed') @@ -5252,7 +5300,7 @@ putAcceptThirdPartyCookieEnabled(accept: boolean): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('putAcceptThirdPartyCookieEnabled') @@ -5285,7 +5333,7 @@ existCookie(): boolean @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('existCookie') @@ -5313,7 +5361,7 @@ deleteEntireCookie(): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('deleteEntireCookie') @@ -5340,7 +5388,7 @@ deleteSessionCookie(): void @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('deleteSessionCookie') @@ -5640,7 +5688,7 @@ setPorts(ports: Array\): void struct WebComponent { controller: WebController = new WebController() ports: WebMessagePort[] = null - + build() { Column() { Button('setPorts') diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-time.md b/zh-cn/application-dev/reference/errorcodes/errorcode-time.md new file mode 100644 index 0000000000000000000000000000000000000000..1ceca485130c9cb34734cd37c23f04b3c6249054 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-time.md @@ -0,0 +1,24 @@ +# 时间时区服务错误码 + +## -1 锁屏服务异常 + +**错误信息** + + The parameter check failed or permission denied or system error. + +**错误描述** + +参数校验失败、权限校验失败或者时间时区服务异常。 + +**可能原因** + +该错误码代表一种通用错误码,可根据错误信息判断具体异常,可能原因如下: +1. 参数校验失败,传入参数无效。 +2. 权限校验失败,权限未配置。应用设置时间未配置ohos.permission.SET_TIME或者设置时区未配置ohos.permission.SET_TIME_ZONE。 +3. 系统运行异常。内存申请、多线程处理等内核通用错误。 + +**处理步骤** + +1. 参数校验失败,传入参数无效。检查参数是否按照要求传入。 +2. 权限校验失败,应用设置时间配置ohos.permission.SET_TIME或者设置时区配置ohos.permission.SET_TIME_ZONE。 +3. 系统运行异常。确认内存是否足够。 diff --git a/zh-cn/application-dev/reference/native-apis/Readme-CN.md b/zh-cn/application-dev/reference/native-apis/Readme-CN.md index 523617f1f2b955e98d8274d870b061cc87c6b4f5..7aa501d67905d674319e612f0a6ed9ad792707af 100644 --- a/zh-cn/application-dev/reference/native-apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/native-apis/Readme-CN.md @@ -12,7 +12,6 @@ - [Rawfile](rawfile.md) - [MindSpore](_mind_spore.md) - [NeuralNeworkRuntime](_neural_nework_runtime.md) - - [Avsession](avsession.md) - [AudioDecoder](_audio_decoder.md) - [AudioEncoder](_audio_encoder.md) - [CodecBase](_codec_base.md) @@ -52,16 +51,6 @@ - [types.h](types_8h.md) - [neural_network_runtime_type.h](neural__network__runtime__type_8h.md) - [neural_network_runtime.h](neural__network__runtime_8h.md) - - [av_session.h](av__session_8h.md) - - [avcontrol_command.h](avcontrol__command_8h.md) - - [avmeta_data.h](avmeta__data_8h.md) - - [avplayback_state.h](avplayback__state_8h.md) - - [avsession_controller.h](avsession__controller_8h.md) - - [avsession_descriptor.h](avsession__descriptor_8h.md) - - [avsession_errors.h](avsession__errors_8h.md) - - [avsession_info.h](avsession__info_8h.md) - - [avsession_manager.h](avsession__manager_8h.md) - - [avsession_pixel_map.h](avsession__pixel__map_8h.md) - [native_avcodec_audiodecoder.h](native__avcodec__audiodecoder_8h.md) - [native_avcodec_audioencoder.h](native__avcodec__audioencoder_8h.md) - [native_avcodec_base.h](native__avcodec__base_8h.md) @@ -96,21 +85,6 @@ - [OH_NN_UInt32Array](_o_h___n_n___u_int32_array.md) - [OH_AVCodecAsyncCallback](_o_h___a_v_codec_async_callback.md) - [OH_AVCodecBufferAttr](_o_h___a_v_codec_buffer_attr.md) - - [OHOS::AVSession::AVControlCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md) - - [OHOS::AVSession::AVControllerCallback](_h_o_s_1_1_a_v_session_1_1_a_v_controller_callback.md) - - [OHOS::AVSession::AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md) - - [OHOS::AVSession::AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md) - - [OHOS::AVSession::AVPlaybackState::Position](_1_a_v_session_1_1_a_v_playback_state_1_1_position.md) - - [OHOS::AVSession::AVSession](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md) - - [OHOS::AVSession::AVSessionBasicInfo](o_h_o_s_1_1_a_v_session_1_1_a_v_session_basic_info.md) - - [OHOS::AVSession::AVSessionCallback](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_callback.md) - - [OHOS::AVSession::AVSessionController](o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md) - - [OHOS::AVSession::AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) - - [OHOS::AVSession::AVSessionManager](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_manager.md) - - [OHOS::AVSession::AVSessionPixelMap](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md) - - [OHOS::AVSession::OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md) - - [OHOS::AVSession::SessionListener](_o_h_o_s_1_1_a_v_session_1_1_session_listener.md) - - [OHOS::AVSession::SessionToken](_o_h_o_s_1_1_a_v_session_1_1_session_token.md) - [OH_Huks_Blob](_o_h___huks___blob.md) - [OH_Huks_CertChain](_o_h___huks___cert_chain.md) - [OH_Huks_KeyInfo](_o_h___huks___key_info.md) diff --git a/zh-cn/application-dev/reference/native-apis/_1_a_v_session_1_1_a_v_playback_state_1_1_position.md b/zh-cn/application-dev/reference/native-apis/_1_a_v_session_1_1_a_v_playback_state_1_1_position.md deleted file mode 100644 index c9c21886df62666e25200db386d53a033899b2c6..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_1_a_v_session_1_1_a_v_playback_state_1_1_position.md +++ /dev/null @@ -1,42 +0,0 @@ -# OHOS::AVSession::AVPlaybackState::Position - - -## 概述 - -播放位置的相关信息。 - -**起始版本:** -9 - -## 汇总 - - -### 成员变量 - -| 名称 | 描述 | -| -------- | -------- | -| [elapsedTime_](#elapsedtime) {} | int64_t
媒体已经播放的时间点,第x ms,单位为ms  | -| [updateTime_](#updatetime) {} | int64_t
更新的时间戳,单位为ms  | - - -## 结构体成员变量说明 - - -### elapsedTime_ - - -``` -int64_t OHOS::AVSession::AVPlaybackState::Position::elapsedTime_ {} -``` -**描述:** -媒体已经播放的时间点,第x ms,单位为ms - - -### updateTime_ - - -``` -int64_t OHOS::AVSession::AVPlaybackState::Position::updateTime_ {} -``` -**描述:** -更新的时间戳,单位为ms diff --git a/zh-cn/application-dev/reference/native-apis/_h_o_s_1_1_a_v_session_1_1_a_v_controller_callback.md b/zh-cn/application-dev/reference/native-apis/_h_o_s_1_1_a_v_session_1_1_a_v_controller_callback.md deleted file mode 100644 index e22742620f0f43a66c788c723f95e349b2a70b78..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_h_o_s_1_1_a_v_session_1_1_a_v_controller_callback.md +++ /dev/null @@ -1,136 +0,0 @@ -# OHOS::AVSession::AVControllerCallback - - -## 概述 - -定义控制器相关回调操作的类的实现。 - -**起始版本:** -9 - -## 汇总 - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [OnSessionDestroy](#onsessiondestroy) ()=0 | AVSession会话销毁的抽象的回调方法。  | -| [OnPlaybackStateChange](#onplaybackstatechange) (const [AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md) &state)=0 | 音视频的播放状态发生改变的抽象的回调方法。  | -| [OnMetaDataChange](#onmetadatachange) (const [AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md) &data)=0 | 会话元数据内容发生变化的抽象的回调方法。  | -| [OnActiveStateChange](#onactivestatechange) (bool isActive)=0 | 当前会话激活状态发生改变的抽象的回调方法。  | -| [OnValidCommandChange](#onvalidcommandchange) (const std::vector< int32_t > &cmds)=0 | 控制命令的有效性发生变化的抽象的回调方法。  | -| [OnOutputDeviceChange](#onoutputdevicechange) (const [OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md) &outputDeviceInfo)=0 | 注册会话输出设备更改。  | -| [~AVControllerCallback](#avcontrollercallback) ()=default | AVControllerCallback的默认的析构函数。  | - - -## 构造及析构函数说明 - - -### ~AVControllerCallback() - - -``` -virtual OHOS::AVSession::AVControllerCallback::~AVControllerCallback () -``` -**描述:** -AVControllerCallback的默认的析构函数。 - - -## 成员函数说明 - - -### OnActiveStateChange() - - -``` -virtual void OHOS::AVSession::AVControllerCallback::OnActiveStateChange (bool isActive) -``` -**描述:** -当前会话激活状态发生改变的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| isActive | 表示是否激活。  | - - -### OnMetaDataChange() - - -``` -virtual void OHOS::AVSession::AVControllerCallback::OnMetaDataChange (const AVMetaData & data) -``` -**描述:** -会话元数据内容发生变化的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 会话元数据内容,类型为[AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md)。  | - -**参见:** - -[AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md) - - -### OnOutputDeviceChange() - - -``` -virtual void OHOS::AVSession::AVControllerCallback::OnOutputDeviceChange (const OutputDeviceInfo & outputDeviceInfo) -``` -**描述:** -注册会话输出设备更改。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| outputDeviceInfo | 输出设备信息 [OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md)。  | - - -### OnPlaybackStateChange() - - -``` -virtual void OHOS::AVSession::AVControllerCallback::OnPlaybackStateChange (const AVPlaybackState & state) -``` -**描述:** -音视频的播放状态发生改变的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| state | 音视频的播放状态的枚举值,类型为[AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md)。  | - - -### OnSessionDestroy() - - -``` -virtual void OHOS::AVSession::AVControllerCallback::OnSessionDestroy () -``` -**描述:** -AVSession会话销毁的抽象的回调方法。 - - -### OnValidCommandChange() - - -``` -virtual void OHOS::AVSession::AVControllerCallback::OnValidCommandChange (const std::vector< int32_t > & cmds) -``` -**描述:** -控制命令的有效性发生变化的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| cmds,媒体有效的指令列表,范围为{ | | - - \ No newline at end of file diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md deleted file mode 100644 index b6af07bf0fac8b7b4a6f0fabae9205b57c8ebef5..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md +++ /dev/null @@ -1,400 +0,0 @@ -# OHOS::AVSession::AVControlCommand - - -## 概述 - -用于描述音视频播控命令工具类,播控命令的封装对象,支持设置和获取控制命令。 - - -## 汇总 - - -### Public 类型 - - | 名称 | 描述 | -| -------- | -------- | -| {
**SESSION_CMD_INVALID** = -1, **SESSION_CMD_PLAY** = 0, **SESSION_CMD_PAUSE** = 1, **SESSION_CMD_STOP** = 2, **SESSION_CMD_PLAY_NEXT** = 3, **SESSION_CMD_PLAY_PREVIOUS** = 4, **SESSION_CMD_FAST_FORWARD** = 5, **SESSION_CMD_REWIND** = 6, **SESSION_CMD_SEEK** = 7, **SESSION_CMD_SET_SPEED** = 8, **SESSION_CMD_SET_LOOP_MODE** = 9, **SESSION_CMD_TOGGLE_FAVORITE** = 10, **SESSION_CMD_MAX** = 11
} | 操作指令。 | - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [Marshalling](#marshalling) (Parcel &parcel) const override | IPC通信数据序列化。 | - - -### 静态 Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [Unmarshalling](#unmarshalling) (Parcel &data) | IPC通信数据反序列化。 | -| [localCapability](#localcapability) | 命令数组,用于分布式业务,判断是否支持某个命令。 | -| [IsValid](#isvalid) () const | 判断当前指令是否在有效范围内。 | -| [SetCommand](#setcommand) (int32_t cmd) | 设置操作指令。 | -| [GetCommand](#getcommand) () const | 获取操作指令。 | -| [SetSpeed](#setspeed) (double speed) | 设置媒体播放倍数。 | -| [GetSpeed](#getspeed) (double &speed) const | 获取媒体播放倍数 | -| [SetSeekTime](#setseektime) (int64_t time) | 设置媒体跳播时间。 | -| [GetSeekTime](#getseektime) (int64_t &time) const | 获取媒体跳播时间。 | -| [SetLoopMode](#setloopmode) (int32_t mode) | 设置媒体循环模式。 | -| [GetLoopMode](#getloopmode) (int32_t &mode) const | 获取媒体循环模式。 | -| [SetAssetId](#setassetid) (const std::string &assetId) | 设置媒体id。 | -| [GetAssetId](#getassetid) (std::string &assetId) const | 获取媒体id。 | - - -## 成员枚举类型说明 - - -### anonymous enum - - -``` -anonymous enum -``` -**描述:** -操作指令。 - - | 枚举值 | 描述 | -| -------- | -------- | -| SESSION_CMD_INVALID | 无效指令,内部用于判断指令是否有效 | -| SESSION_CMD_PLAY | 播放 | -| SESSION_CMD_PAUSE | 暂停 | -| SESSION_CMD_STOP | 停止 | -| SESSION_CMD_PLAY_NEXT | 播放下一首 | -| SESSION_CMD_PLAY_PREVIOUS | 播放上一首 | -| SESSION_CMD_FAST_FORWARD | 快进 | -| SESSION_CMD_REWIND | 快退 | -| SESSION_CMD_SEEK | 跳播 | -| SESSION_CMD_SET_SPEED | 设置播放倍数 | -| SESSION_CMD_SET_LOOP_MODE | 设置循环模式 | -| SESSION_CMD_TOGGLE_FAVORITE | 收藏 | -| SESSION_CMD_MAX | 无效指令,内部用于判断指令是否有效 | - - -## 成员函数说明 - - -### GetAssetId() - - -``` -int32_t OHOS::AVSession::AVControlCommand::GetAssetId (std::string & assetId) const -``` -**描述:** -获取媒体id。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| assetId | 保存媒体id。 | - -**参见:** - -[SetAssetId](#setassetid) - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### GetCommand() - - -``` -int32_t OHOS::AVSession::AVControlCommand::GetCommand () const -``` -**描述:** -获取操作指令。 - -**返回:** - -返回操作指令,范围在**SESSION_CMD_INVALID**到**SESSION_CMD_MAX**之间。 - -**参见:** - -[SetCommand](#setcommand) - - -### GetLoopMode() - - -``` -int32_t OHOS::AVSession::AVControlCommand::GetLoopMode (int32_t & mode) const -``` -**描述:** -获取媒体循环模式。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mode | 保存媒体循环模式。 取值在[AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md)的**LOOP_MODE_SEQUENCE**到**LOOP_MODE_SHUFFLE**之间。 | - -**参见:** - -[SetLoopMode](#setloopmode) - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### GetSeekTime() - - -``` -int32_t OHOS::AVSession::AVControlCommand::GetSeekTime (int64_t & time) const -``` -**描述:** -获取媒体跳播时间。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| time | 媒体资源的位置,从媒体资源开头开始计算,单位为ms。取值需大于等于0。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[SetSeekTime](#setseektime) - - -### GetSpeed() - - -``` -int32_t OHOS::AVSession::AVControlCommand::GetSpeed (double & speed) const -``` -**描述:** -获取媒体播放倍数 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| speed | 媒体播放倍数,返回值。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[SetSpeed](#setspeed) - - -### IsValid() - - -``` -bool OHOS::AVSession::AVControlCommand::IsValid () const -``` -**描述:** -判断当前指令是否在有效范围内。 - -**返回:** - -如果cmd_在有效范围内,范围在**SESSION_CMD_INVALID**到**SESSION_CMD_MAX**之间, 返回true;否则,返回false。 - - -### Marshalling() - - -``` -bool OHOS::AVSession::AVControlCommand::Marshalling (Parcel & parcel) const -``` -**描述:** -IPC通信数据序列化。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| parcel | 保存序列化值的对象**Parcel**。 | - -**返回:** - -成功返回true;否则,返回false。 - -**参见:** - -[Unmarshalling](#unmarshalling) - - -### SetAssetId() - - -``` -int32_t OHOS::AVSession::AVControlCommand::SetAssetId (const std::string & assetId) -``` -**描述:** -设置媒体id。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| assetId | 媒体id,不可为空。 | - -**参见:** - -[GetAssetId](#getassetid) - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### SetCommand() - - -``` -int32_t OHOS::AVSession::AVControlCommand::SetCommand (int32_t cmd) -``` -**描述:** -设置操作指令。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| cmd | 操作指令,范围在**SESSION_CMD_INVALID**到**SESSION_CMD_MAX**之间。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[GetCommand](#getcommand) - - -### SetLoopMode() - - -``` -int32_t OHOS::AVSession::AVControlCommand::SetLoopMode (int32_t mode) -``` -**描述:** -设置媒体循环模式。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mode | 媒体循环模式, 取值在[AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md)的**LOOP_MODE_SEQUENCE**到**LOOP_MODE_SHUFFLE**之间。 | - -**参见:** - -[GetLoopMode](#getloopmode) - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### SetSeekTime() - - -``` -int32_t OHOS::AVSession::AVControlCommand::SetSeekTime (int64_t time) -``` -**描述:** -设置媒体跳播时间。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| time | 媒体资源的位置,从媒体资源开头开始计算,单位为ms。取值需大于等于0。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[GetSeekTime](#getseektime) - - -### SetSpeed() - - -``` -int32_t OHOS::AVSession::AVControlCommand::SetSpeed (double speed) -``` -**描述:** -设置媒体播放倍数。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| speed | 媒体播放倍数,需大于0。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[GetSpeed](#getspeed) - - -### Unmarshalling() - - -``` -static AVControlCommand* OHOS::AVSession::AVControlCommand::Unmarshalling (Parcel & data) -``` -**描述:** -IPC通信数据反序列化。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 序列化对象**Parcel**。 | - -**返回:** - -返回AVControlCommand的函数指针。 - -**参见:** - -[Marshalling](#marshalling) - - -## 结构体成员变量说明 - - -### localCapability - - -``` -const std::vector OHOS::AVSession::AVControlCommand::localCapability -``` -**Value:** - -``` -{ - SESSION_CMD_PLAY, - SESSION_CMD_PAUSE, - SESSION_CMD_STOP, - SESSION_CMD_PLAY_NEXT, - SESSION_CMD_PLAY_PREVIOUS, - SESSION_CMD_FAST_FORWARD, - SESSION_CMD_REWIND, - SESSION_CMD_SEEK, - SESSION_CMD_SET_SPEED, - SESSION_CMD_SET_LOOP_MODE, - SESSION_CMD_TOGGLE_FAVORITE, - } -``` -**描述:** -命令数组,用于分布式业务,判断是否支持某个命令。 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md deleted file mode 100644 index 2300db5d2dbd054a9a1ae2386c1f509c1447ff07..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md +++ /dev/null @@ -1,926 +0,0 @@ -# OHOS::AVSession::AVMetaData - - -## 概述 - -会话元数据类,提供获取metadata进程间传递的序列化和反序列话及数据拷贝的接口方法。 - - -## 汇总 - - -### Public 类型 - - | 名称 | 描述 | -| -------- | -------- | -| {
**META_KEY_ASSET_ID** = 0, **META_KEY_TITLE** = 1, **META_KEY_ARTIST** = 2, **META_KEY_AUTHOR** = 3, **META_KEY_ALBUM** = 4, **META_KEY_WRITER** = 5, **META_KEY_COMPOSER** = 6, **META_KEY_DURATION** = 7, **META_KEY_MEDIA_IMAGE** = 8, **META_KEY_MEDIA_IMAGE_URI** = 9, **META_KEY_PUBLISH_DATE** = 10, **META_KEY_SUBTITLE** = 11, **META_KEY_DESCRIPTION** = 12, **META_KEY_LYRIC** = 13, **META_KEY_PREVIOUS_ASSET_ID** = 14, **META_KEY_NEXT_ASSET_ID** = 15, **META_KEY_MAX** = 16
} | 会话元数据具体枚举项。 | -| [MetaMaskType](#metamasktype) = std::bitset< META_KEY_MAX > | 引入掩码标记需要拷贝的会话元数据。 | - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [AVMetaData](#avmetadata) ()=default | 会话元数据默认构造函数。 | -| [~AVMetaData](#avmetadata) () override | 会话元数据默认析构函数。 | -| [Marshalling](#marshalling) (Parcel &data) const override | 实现会话元数据进程间传递的序列化。 | -| [SetAssetId](#setassetid) (const std::string &assetId) | 设置曲目ID。 | -| [GetAssetId](#getassetid) () const | 获取曲目ID。 | -| [SetTitle](#settitle) (const std::string &title) | 设置标题。 | -| [GetTitle](#gettitle) () const | 获取标题。 | -| [SetArtist](#setartist) (const std::string &artist) | 设置艺术家名称。 | -| [GetArtist](#getartist) () const | 获取艺术家名称。 | -| [SetAuthor](#setauthor) (const std::string &author) | 设置制作人名称。 | -| [GetAuthor](#getauthor) () const | 获取制作人名称。 | -| [SetAlbum](#setalbum) (const std::string &album) | 设置专辑名称。 | -| [GetAlbum](#getalbum) () const | 获取专辑名称。 | -| [SetWriter](#setwriter) (const std::string &writer) | 设置作词名称。 | -| [GetWriter](#getwriter) () const | 获取作词名称。 | -| [SetComposer](#setcomposer) (const std::string &composer) | 设置作曲名称。 | -| [GetComposer](#getcomposer) () const | 获取作曲名称。 | -| [SetDuration](#setduration) (int64_t duration) | 设置媒体时长。 | -| [GetDuration](#getduration) () const | 获取媒体时长。 | -| [SetMediaImage](#setmediaimage) (const std::shared_ptr< [AVSessionPixelMap](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md) > &mediaImage) | 设置媒体图片。 | -| [GetMediaImage](#getmediaimage) () const | 获取媒体图片。 | -| [SetMediaImageUri](#setmediaimageuri) (const std::string &mediaImageUri) | 设置媒体图片URI。 | -| [GetMediaImageUri](#getmediaimageuri) () const | 获取媒体图片URI。 | -| [SetPublishDate](#setpublishdate) (double date) | 设置曲目发布日期,时间戳,单位为ms。 | -| [GetPublishDate](#getpublishdate) () const | 获取曲目发布日期,时间戳,单位为ms。 | -| [SetSubTitle](#setsubtitle) (const std::string &subTitle) | 设置子标题。 | -| [GetSubTitle](#getsubtitle) () const | 获取子标题。 | -| [SetDescription](#setdescription) (const std::string &description) | 设置曲目描述。 | -| [GetDescription](#getdescription) () const | 获取曲目描述。 | -| [SetLyric](#setlyric) (const std::string &lyric) | 设置歌词。 | -| [GetLyric](#getlyric) () const | 获取歌词。 | -| [SetPreviousAssetId](#setpreviousassetid) (const std::string &assetId) | 设置上一曲曲目ID。 | -| [GetPreviousAssetId](#getpreviousassetid) () const | 获取上一曲曲目ID。 | -| [SetNextAssetId](#setnextassetid) (const std::string &assetId) | 设置下一曲曲目ID。 | -| [GetNextAssetId](#getnextassetid) () const | 获取下一曲曲目ID。 | -| [Reset](#reset) () | 重置所有会话元数据项。 | -| [GetMetaMask](#getmetamask) () const | 获取掩码。 | -| [CopyToByMask](#copytobymask) ([MetaMaskType](#metamasktype) &mask, AVMetaData &metaOut) const | 根据metadata掩码,将metadata项复制到metaOut。 | -| [CopyFrom](#copyfrom) (const AVMetaData &metaIn) | 根据metaIn元掩码的设置位从metaIn复制metadata项。 | -| [IsValid](#isvalid) () const | 会话元数据有效性判断。 | - - -### 静态 Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [Unmarshalling](#unmarshalling) (Parcel &data) | 实现会话元数据进程间传递的反序列化。 | - - -### 静态 Public 属性 - - | 名称 | 描述 | -| -------- | -------- | -| [DURATION_ALWAYS_PLAY](#duration_always_play) = -1 | 持续时间全局变量宏定义。 | -| [localCapability](#localcapability) | 会话元数据数组,用于分布式业务,设置会话属性。 | - - -## 成员类型定义说明 - - -### MetaMaskType - - -``` -using OHOS::AVSession::AVMetaData::MetaMaskType = std::bitset -``` -**描述:** -引入掩码标记需要拷贝的会话元数据。 - - -## 成员枚举类型说明 - - -### anonymous enum - - -``` -anonymous enum -``` -**描述:** -会话元数据具体枚举项。 - - | 枚举值 | 描述 | -| -------- | -------- | -| META_KEY_ASSET_ID | 曲目ID | -| META_KEY_TITLE | 标题 | -| META_KEY_ARTIST | 艺术家 | -| META_KEY_AUTHOR | 制作人 | -| META_KEY_ALBUM | 专辑 | -| META_KEY_WRITER | 作词 | -| META_KEY_COMPOSER | 作曲 | -| META_KEY_DURATION | 媒体时长 | -| META_KEY_MEDIA_IMAGE | 媒体影像 | -| META_KEY_MEDIA_IMAGE_URI | 媒体影像路径 | -| META_KEY_PUBLISH_DATE | 曲目发布日期 | -| META_KEY_SUBTITLE | 子标题 | -| META_KEY_DESCRIPTION | 曲目描述 | -| META_KEY_LYRIC | 歌词 | -| META_KEY_PREVIOUS_ASSET_ID | 上一曲 | -| META_KEY_NEXT_ASSET_ID | 下一曲 | -| META_KEY_MAX | 无效指令,内部用来判断会话元数据是否有效 | - - -## 构造及析构函数说明 - - -### AVMetaData() - - -``` -OHOS::AVSession::AVMetaData::AVMetaData () -``` -**描述:** -会话元数据默认构造函数。 - - -### ~AVMetaData() - - -``` -OHOS::AVSession::AVMetaData::~AVMetaData () -``` -**描述:** -会话元数据默认析构函数。 - - -## 成员函数说明 - - -### CopyFrom() - - -``` -bool OHOS::AVSession::AVMetaData::CopyFrom (const AVMetaData & metaIn) -``` -**描述:** -根据metaIn元掩码的设置位从metaIn复制metadata项。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| metaIn | 会话元数据将要拷贝的入参。| - - -### CopyToByMask() - - -``` -bool OHOS::AVSession::AVMetaData::CopyToByMask (MetaMaskType & mask, AVMetaData & metaOut ) const -``` -**描述:** -根据metadata掩码,将metadata项复制到metaOut。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mask | metadata掩码[MetaMaskType](#metamasktype)。 | -| metaOut | metadata已拷贝成功的出参AVMetaData。 | - -**返回:** - -成功返回true;失败则返回false。 - - -### GetAlbum() - - -``` -std::string OHOS::AVSession::AVMetaData::GetAlbum () const -``` -**描述:** -获取专辑名称。 - -**返回:** - -返回专辑名称。 - -**参见:** - -[SetAlbum](#setalbum) - - -### GetArtist() - - -``` -std::string OHOS::AVSession::AVMetaData::GetArtist () const -``` -**描述:** -获取艺术家名称。 - -**返回:** - -返回艺术家名称。 - -**参见:** - -[SetArtist](#setartist) - - -### GetAssetId() - - -``` -std::string OHOS::AVSession::AVMetaData::GetAssetId () const -``` -**描述:** -获取曲目ID。 - -**返回:** - -返回曲目ID。 - -**参见:** - -[SetAssetId](#setassetid) - - -### GetAuthor() - - -``` -std::string OHOS::AVSession::AVMetaData::GetAuthor () const -``` -**描述:** -获取制作人名称。 - -**返回:** - -返回制作人名称。 - -**参见:** - -[SetAuthor](#setauthor) - - -### GetComposer() - - -``` -std::string OHOS::AVSession::AVMetaData::GetComposer () const -``` -**描述:** -获取作曲名称。 - -**返回:** - -返回作曲名称。 - -**参见:** - -[SetComposer](#setcomposer) - - -### GetDescription() - - -``` -std::string OHOS::AVSession::AVMetaData::GetDescription () const -``` -**描述:** -获取曲目描述。 - -**返回:** - -返回曲目描述。 - -**参见:** - -[SetDescription](#setdescription) - - -### GetDuration() - - -``` -int64_t OHOS::AVSession::AVMetaData::GetDuration () const -``` -**描述:** -获取媒体时长。 - -**返回:** - -返回媒体时长,单位为ms。 - -**参见:** - -[SetDuration](#setduration) - - -### GetLyric() - - -``` -std::string OHOS::AVSession::AVMetaData::GetLyric () const -``` -**描述:** -获取歌词。 - -**返回:** - -返回歌词。 - -**参见:** - -[SetLyric](#setlyric) - - -### GetMediaImage() - - -``` -std::shared_ptr OHOS::AVSession::AVMetaData::GetMediaImage () const -``` -**描述:** -获取媒体图片。 - -**返回:** - -返回媒体图片[AVSessionPixelMap](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md)。 - -**参见:** - -[SetMediaImage](#setmediaimage) - - -### GetMediaImageUri() - - -``` -std::string OHOS::AVSession::AVMetaData::GetMediaImageUri () const -``` -**描述:** -获取媒体图片URI。 - -**返回:** - -返回媒体图片URI。 - -**参见:** - -[SetMediaImageUri](#setmediaimageuri) - - -### GetMetaMask() - - -``` -MetaMaskType OHOS::AVSession::AVMetaData::GetMetaMask () const -``` -**描述:** -获取掩码。 - -**返回:** - -返回掩码[MetaMaskType](#metamasktype)。 - - -### GetNextAssetId() - - -``` -std::string OHOS::AVSession::AVMetaData::GetNextAssetId () const -``` -**描述:** -获取下一曲曲目ID。 - -**返回:** - -返回下一曲曲目ID。 - -**参见:** - -[SetNextAssetId](#setnextassetid) - - -### GetPreviousAssetId() - - -``` -std::string OHOS::AVSession::AVMetaData::GetPreviousAssetId () const -``` -**描述:** -获取上一曲曲目ID。 - -**返回:** - -返回上一曲曲目ID。 - -**参见:** - -[SetPreviousAssetId](#setpreviousassetid) - - -### GetPublishDate() - - -``` -double OHOS::AVSession::AVMetaData::GetPublishDate () const -``` -**描述:** -获取曲目发布日期,时间戳,单位为ms。 - -**返回:** - -返回曲目发布日期,时间戳,单位为ms。 - -**参见:** - -[SetPublishDate](#setpublishdate) - - -### GetSubTitle() - - -``` -std::string OHOS::AVSession::AVMetaData::GetSubTitle () const -``` -**描述:** -获取子标题。 - -**返回:** - -返回子标题。 - -**参见:** - -[SetSubTitle](#setsubtitle) - - -### GetTitle() - - -``` -std::string OHOS::AVSession::AVMetaData::GetTitle () const -``` -**描述:** -获取标题。 - -**返回:** - -返回标题。 - -**参见:** - -[SetTitle](#settitle) - - -### GetWriter() - - -``` -std::string OHOS::AVSession::AVMetaData::GetWriter () const -``` -**描述:** -获取作词名称。 - -**返回:** - -返回作词名称。 - -**参见:** - -[SetWriter](#setwriter) - - -### IsValid() - - -``` -bool OHOS::AVSession::AVMetaData::IsValid () const -``` -**描述:** -会话元数据有效性判断。 - -**返回:** - -有效返回true;无效则返回false。 - - -### Marshalling() - - -``` -bool OHOS::AVSession::AVMetaData::Marshalling (Parcel & data) const -``` -**描述:** -实现会话元数据进程间传递的序列化。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 保存序列化值的对象**Parcel**。 | - -**返回:** - -如果序列化成功,则返回true;如果操作失败,则返回false。 - -**参见:** - -[Unmarshalling](#unmarshalling) - - -### Reset() - - -``` -void OHOS::AVSession::AVMetaData::Reset () -``` -**描述:** -重置所有会话元数据项。 - - -### SetAlbum() - - -``` -void OHOS::AVSession::AVMetaData::SetAlbum (const std::string & album) -``` -**描述:** -设置专辑名称。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| album | 专辑名称。 | - -**参见:** - -[GetAlbum](#getalbum) - - -### SetArtist() - - -``` -void OHOS::AVSession::AVMetaData::SetArtist (const std::string & artist) -``` -**描述:** -设置艺术家名称。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| artist | 艺术家名称。 | - -**参见:** - -[GetArtist](#getartist) - - -### SetAssetId() - - -``` -void OHOS::AVSession::AVMetaData::SetAssetId (const std::string & assetId) -``` -**描述:** -设置曲目ID。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| assetId | 曲目ID,不可为空。 | - -**参见:** - -[GetAssetId](#getassetid) - - -### SetAuthor() - - -``` -void OHOS::AVSession::AVMetaData::SetAuthor (const std::string & author) -``` -**描述:** -设置制作人名称。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| author | 制作人名称。 | - -**参见:** - -[GetArtist](#getartist) - - -### SetComposer() - - -``` -void OHOS::AVSession::AVMetaData::SetComposer (const std::string & composer) -``` -**描述:** -设置作曲名称。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| composer | 作曲名称。 | - -**参见:** - -[GetComposer](#getcomposer) - - -### SetDescription() - - -``` -void OHOS::AVSession::AVMetaData::SetDescription (const std::string & description) -``` -**描述:** -设置曲目描述。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| description | 曲目描述。 | - -**参见:** - -[GetDescription](#getdescription) - - -### SetDuration() - - -``` -void OHOS::AVSession::AVMetaData::SetDuration (int64_t duration) -``` -**描述:** -设置媒体时长。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| duration | 媒体时长,必须大于等于-1,单位为ms 。 | - -**参见:** - -[GetDuration](#getduration) - - -### SetLyric() - - -``` -void OHOS::AVSession::AVMetaData::SetLyric (const std::string & lyric) -``` -**描述:** -设置歌词。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| lyric | 歌词。 | - -**参见:** - -[GetLyric](#getlyric) - - -### SetMediaImage() - - -``` -void OHOS::AVSession::AVMetaData::SetMediaImage (const std::shared_ptr< AVSessionPixelMap > & mediaImage) -``` -**描述:** -设置媒体图片。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mediaImage | 媒体图片[AVSessionPixelMap](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md)。 | - -**参见:** - -[GetMediaImage](#getmediaimage) - - -### SetMediaImageUri() - - -``` -void OHOS::AVSession::AVMetaData::SetMediaImageUri (const std::string & mediaImageUri) -``` -**描述:** -设置媒体图片URI。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mediaImageUri | 媒体图片URI。 | - -**参见:** - -[GetMediaImageUri](#getmediaimageuri) - - -### SetNextAssetId() - - -``` -void OHOS::AVSession::AVMetaData::SetNextAssetId (const std::string & assetId) -``` -**描述:** -设置下一曲曲目ID。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| assetId | 下一曲曲目ID。 | - -**参见:** - -[GetNextAssetId](#getnextassetid) - - -### SetPreviousAssetId() - - -``` -void OHOS::AVSession::AVMetaData::SetPreviousAssetId (const std::string & assetId) -``` -**描述:** -设置上一曲曲目ID。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| assetId | 上一曲曲目ID。 | - -**参见:** - -[GetPreviousAssetId](#getpreviousassetid) - - -### SetPublishDate() - - -``` -void OHOS::AVSession::AVMetaData::SetPublishDate (double date) -``` -**描述:** -设置曲目发布日期,时间戳,单位为ms。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| date | 曲目发布日期,时间戳,单位为ms。 | - -**参见:** - -[GetPublishDate](#getpublishdate) - - -### SetSubTitle() - - -``` -void OHOS::AVSession::AVMetaData::SetSubTitle (const std::string & subTitle) -``` -**描述:** -设置子标题。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| subTitle | 子标题。 | - -**参见:** - -[GetSubTitle](#getsubtitle) - - -### SetTitle() - - -``` -void OHOS::AVSession::AVMetaData::SetTitle (const std::string & title) -``` -**描述:** -设置标题。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| title | 标题。 | - -**参见:** - -[GetTitle](#gettitle) - - -### SetWriter() - - -``` -void OHOS::AVSession::AVMetaData::SetWriter (const std::string & writer) -``` -**描述:** -设置作词名称。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| writer | 作词名称。 | - -**参见:** - -[GetWriter](#getwriter) - - -### Unmarshalling() - - -``` -static AVMetaData* OHOS::AVSession::AVMetaData::Unmarshalling (Parcel & data) -``` -**描述:** -实现会话元数据进程间传递的反序列化。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 序列化对象**Parcel**。 | - -**返回:** - -如果反序列化成功,返回AVMetaData类型指针;失败则返回nullptr。 - -**参见:** - -[Marshalling](#marshalling) - - -## 结构体成员变量说明 - - -### DURATION_ALWAYS_PLAY - - -``` -constexpr std::int64_t OHOS::AVSession::AVMetaData::DURATION_ALWAYS_PLAY = -1 -``` -**描述:** -持续时间全局变量宏定义。 - - -### localCapability - - -``` -const std::vector OHOS::AVSession::AVMetaData::localCapability -``` -**Value:** - -``` -{ - META_KEY_ASSET_ID, - META_KEY_TITLE, - META_KEY_ARTIST, - META_KEY_AUTHOR, - META_KEY_ALBUM, - META_KEY_WRITER, - META_KEY_COMPOSER, - META_KEY_DURATION, - META_KEY_MEDIA_IMAGE, - META_KEY_MEDIA_IMAGE_URI, - META_KEY_PUBLISH_DATE, - META_KEY_SUBTITLE, - META_KEY_DESCRIPTION, - META_KEY_LYRIC, - META_KEY_PREVIOUS_ASSET_ID, - META_KEY_NEXT_ASSET_ID, - } -``` -**描述:** -会话元数据数组,用于分布式业务,设置会话属性。 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md deleted file mode 100644 index 8183b4b57c655174ae3ae217f72a88bec45020c1..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md +++ /dev/null @@ -1,502 +0,0 @@ -# OHOS::AVSession::AVPlaybackState - - -## 概述 - -音视频播放状态类,提供获取和设置播放界面的信息。 - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [Position](_1_a_v_session_1_1_a_v_playback_state_1_1_position.md) | struct
播放位置的相关信息。 | - - -### Public 类型 - - | 名称 | 描述 | -| -------- | -------- | -| {
**PLAYBACK_STATE_INITIAL** = 0, **PLAYBACK_STATE_PREPARING** = 1, **PLAYBACK_STATE_PLAYING** = 2, **PLAYBACK_STATE_PAUSED** = 3, **PLAYBACK_STATE_FAST_FORWARD** = 4, **PLAYBACK_STATE_REWIND** = 5, **PLAYBACK_STATE_STOP** = 6, **PLAYBACK_STATE_MAX** = 7
} | 描述播放状态的枚举。 | -| {
**PLAYBACK_KEY_STATE** = 0, **PLAYBACK_KEY_SPEED** = 1, **PLAYBACK_KEY_POSITION** = 2, **PLAYBACK_KEY_BUFFERED_TIME** = 3, **PLAYBACK_KEY_LOOP_MODE** = 4, **PLAYBACK_KEY_IS_FAVORITE** = 5, **PLAYBACK_KEY_MAX** = 6
} | 播放界面信息的枚举。 | -| { **LOOP_MODE_SEQUENCE** = 0, **LOOP_MODE_SINGLE** = 1, **LOOP_MODE_LIST** = 2, **LOOP_MODE_SHUFFLE** = 3 } | 循环模式的枚举。 | -| **PlaybackStateMaskType** = std::bitset< PLAYBACK_KEY_MAX > | | - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [Marshalling](#marshalling) (Parcel &parcel) const override | IPC通信数据序列化。 | -| [IsValid](#isvalid) () const | 验证当前信息的有效性。 | -| [SetState](#setstate) (int32_t state) | 设置音视频的播放状态。 | -| [GetState](#getstate) () const | 获取当前音视频的播放状态。 | -| [SetSpeed](#setspeed) (double speed) | 设置播放倍速。 | -| [GetSpeed](#getspeed) () const | 获取当前播放倍速。 | -| [SetPosition](#setposition) (const [Position](_1_a_v_session_1_1_a_v_playback_state_1_1_position.md) &position) | 设置播放位置,通过更新时间与经过时间来计算,单位ms。 | -| [GetPosition](#getposition) () const | 获取播放位置。 | -| [SetBufferedTime](#setbufferedtime) (int64_t time) | 设置缓冲时间,单位为ms。 | -| [GetBufferedTime](#getbufferedtime) () const | 获取当前缓冲时间,单位为ms。 | -| [SetLoopMode](#setloopmode) (int32_t mode) | 设置循环模式。 | -| [GetLoopMode](#getloopmode) () const | 获取当前循环模式。 | -| [SetFavorite](#setfavorite) (bool isFavorite) | 设置是否收藏。 | -| [GetFavorite](#getfavorite) () const | 获取是否收藏。 | -| [GetMask](#getmask) () const | 获取掩码。 | - - -### 静态 Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [Unmarshalling](#unmarshalling) (Parcel &parcel) | IPC通信数据反序列化。 | -| [localCapability](#localcapability) | 内联函数指针数组AVPlaybackState,用于分布式业务,设置播放界面信息。 | -| [CopyToByMask](#copytobymask) (PlaybackStateMaskType &mask, AVPlaybackState &out) const | 通过掩码拷贝信息到新的AVPlaybackState对象。 | -| [CopyFrom](#copyfrom) (const AVPlaybackState &in) | 根据当前对象的mask_掩码,将输入的AVPlaybackState类型的信息复制到当前对象。 | - - -## 成员枚举类型说明 - - -### anonymous enum - - -``` -anonymous enum -``` -**描述:** -描述播放状态的枚举。 - - | 枚举值 | 描述 | -| -------- | -------- | -| PLAYBACK_STATE_INITIAL | 初始状态 | -| PLAYBACK_STATE_PREPARING | 缓冲状态 | -| PLAYBACK_STATE_PLAYING | 播放状态 | -| PLAYBACK_STATE_PAUSED | 暂停状态 | -| PLAYBACK_STATE_FAST_FORWARD | 快进状态 | -| PLAYBACK_STATE_REWIND | 快退状态 | -| PLAYBACK_STATE_STOP | 停止状态 | -| PLAYBACK_STATE_MAX | 无效类型,内部用于判断状态是否有效 | - - -### anonymous enum - - -``` -anonymous enum -``` -**描述:** -播放界面信息的枚举。 - - | 枚举值 | 描述 | -| -------- | -------- | -| PLAYBACK_KEY_STATE | 播放状态,包括正在播放、暂停、快进等 | -| PLAYBACK_KEY_SPEED | 播放倍数 | -| PLAYBACK_KEY_POSITION | 播放位置 | -| PLAYBACK_KEY_BUFFERED_TIME | 缓冲时间 | -| PLAYBACK_KEY_LOOP_MODE | 循环模式 | -| PLAYBACK_KEY_IS_FAVORITE | 设置喜欢(收藏) | -| PLAYBACK_KEY_MAX | 无效类型,内部用于判断key是否有效 | - - -### anonymous enum - - -``` -anonymous enum -``` -**描述:** -循环模式的枚举。 - - | 枚举值 | 描述 | -| -------- | -------- | -| LOOP_MODE_SEQUENCE | 顺序播放 | -| LOOP_MODE_SINGLE | 单曲循环 | -| LOOP_MODE_LIST | 列表循环 | -| LOOP_MODE_SHUFFLE | 随机播放 | - - -## 成员函数说明 - - -### CopyFrom() - - -``` -bool OHOS::AVSession::AVPlaybackState::CopyFrom (const AVPlaybackState & in) -``` -**描述:** -根据当前对象的mask_掩码,将输入的AVPlaybackState类型的信息复制到当前对象。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| in | AVPlaybackState类型。 | - -**返回:** - -如果有至少一个播放界面信息被拷贝,返回true;如果一个播放界面信息都没有被拷贝,返回false。 - -**参见:** - -[CopyToByMask](#copytobymask) - -[GetMask](#getmask) - - -### CopyToByMask() - - -``` -bool OHOS::AVSession::AVPlaybackState::CopyToByMask (PlaybackStateMaskType & mask, AVPlaybackState & out ) const -``` -**描述:** -通过掩码拷贝信息到新的AVPlaybackState对象。 - -mask对应位上有值的对象拷贝给out。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mask | 输入的掩码**}。 out 输出的音视频的播放状态 AVPlaybackState}。 如果有至少一个播放界面信息被拷贝,返回true;如果一个播放界面信息都没有被拷贝,返回false。 CopyFrom 9 1.0 ** | - - -### GetBufferedTime() - - -``` -int64_t OHOS::AVSession::AVPlaybackState::GetBufferedTime () const -``` -**描述:** -获取当前缓冲时间,单位为ms。 - -**返回:** - -返回缓冲时间。 - -**参见:** - -[SetBufferedTime](#setbufferedtime) - - -### GetFavorite() - - -``` -bool OHOS::AVSession::AVPlaybackState::GetFavorite () const -``` -**描述:** -获取是否收藏。 - -**返回:** - -是否收藏,是则返回true,否则返回false。 - -**参见:** - -[SetFavorite](#setfavorite) - - -### GetLoopMode() - - -``` -int32_t OHOS::AVSession::AVPlaybackState::GetLoopMode () const -``` -**描述:** -获取当前循环模式。 - -**返回:** - -返回循环模式,范围**LOOP_MODE_SEQUENCE**到**LOOP_MODE_SHUFFLE**之间。 - -**参见:** - -[SetLoopMode](#setloopmode) - - -### GetMask() - - -``` -PlaybackStateMaskType OHOS::AVSession::AVPlaybackState::GetMask () const -``` -**描述:** -获取掩码。 - -**返回:** - -返回播放界面信息的掩码**PlaybackStateMaskType**。 - -**参见:** - -[CopyFrom](#copyfrom) - - -### GetPosition() - - -``` -Position OHOS::AVSession::AVPlaybackState::GetPosition () const -``` -**描述:** -获取播放位置。 - -**返回:** - -返回播放位置[Position](_1_a_v_session_1_1_a_v_playback_state_1_1_position.md)。 - -**参见:** - -[SetPosition](#setposition) - - -### GetSpeed() - - -``` -double OHOS::AVSession::AVPlaybackState::GetSpeed () const -``` -**描述:** -获取当前播放倍速。 - -**返回:** - -返回当前播放倍速。 - -**参见:** - -[SetSpeed](#setspeed) - - -### GetState() - - -``` -int32_t OHOS::AVSession::AVPlaybackState::GetState () const -``` -**描述:** -获取当前音视频的播放状态。 - -**返回:** - -返回当前音视频的播放状态,范围**PLAYBACK_STATE_INITIAL**到**PLAYBACK_STATE_MAX**之间。 - -**参见:** - -[SetState](#setstate) - - -### IsValid() - - -``` -bool OHOS::AVSession::AVPlaybackState::IsValid () const -``` -**描述:** -验证当前信息的有效性。 - -**返回:** - -有效返回true;无效则返回false。 - - -### Marshalling() - - -``` -bool OHOS::AVSession::AVPlaybackState::Marshalling (Parcel & parcel) const -``` -**描述:** -IPC通信数据序列化。 - -将AVPlaybackState类型的信息,序列化为**Parcel**类型的信息,用来进行IPC通信。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| parcel | 保存序列化值的对象**Parcel**。 | - -**返回:** - -成功返回true;失败返回false。 - -**参见:** - -[Unmarshalling](#unmarshalling) - - -### SetBufferedTime() - - -``` -void OHOS::AVSession::AVPlaybackState::SetBufferedTime (int64_t time) -``` -**描述:** -设置缓冲时间,单位为ms。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| time | 缓冲时间。 | - -**参见:** - -[GetBufferedTime](#getbufferedtime) - - -### SetFavorite() - - -``` -void OHOS::AVSession::AVPlaybackState::SetFavorite (bool isFavorite) -``` -**描述:** -设置是否收藏。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| isFavorite | 是否收藏,是则为true,否则false。 | - -**参见:** - -[GetFavorite](#getfavorite) - - -### SetLoopMode() - - -``` -void OHOS::AVSession::AVPlaybackState::SetLoopMode (int32_t mode) -``` -**描述:** -设置循环模式。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mode | 循环模式,范围**LOOP_MODE_SEQUENCE**到**LOOP_MODE_SHUFFLE**之间。 | - -**参见:** - -[GetLoopMode](#getloopmode) - - -### SetPosition() - - -``` -void OHOS::AVSession::AVPlaybackState::SetPosition (const Position & position) -``` -**描述:** -设置播放位置,通过更新时间与经过时间来计算,单位ms。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| position | 播放位置[Position](_1_a_v_session_1_1_a_v_playback_state_1_1_position.md)。 | - -**参见:** - -[GetPosition](#getposition) - - -### SetSpeed() - - -``` -void OHOS::AVSession::AVPlaybackState::SetSpeed (double speed) -``` -**描述:** -设置播放倍速。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| speed | 播放倍速。 | - -**参见:** - -[SetSpeed](#setspeed) - - -### SetState() - - -``` -void OHOS::AVSession::AVPlaybackState::SetState (int32_t state) -``` -**描述:** -设置音视频的播放状态。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| state | 音视频的播放状态,范围**PLAYBACK_STATE_INITIAL**到**PLAYBACK_STATE_MAX**之间。 | - -**参见:** - -[GetState](#getstate) - - -### Unmarshalling() - - -``` -static AVPlaybackState* OHOS::AVSession::AVPlaybackState::Unmarshalling (Parcel & parcel) -``` -**描述:** -IPC通信数据反序列化。 - -将通过IPC接收的**Parcel**类型的信息,反序列化为AVPlaybackState类型的信息。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| parcel | 序列化对象**Parcel**。 | - -**返回:** - -如果反序列化成功,则返回AVPlaybackState对象; 如果反序列化失败,则返回nullptr。 - -**参见:** - -[Marshalling](#marshalling) - - -## 结构体成员变量说明 - - -### localCapability - - -``` -const std::vector OHOS::AVSession::AVPlaybackState::localCapability -``` -**Value:** - -``` -{ - PLAYBACK_KEY_STATE, - PLAYBACK_KEY_SPEED, - PLAYBACK_KEY_POSITION, - PLAYBACK_KEY_BUFFERED_TIME, - PLAYBACK_KEY_LOOP_MODE, - PLAYBACK_KEY_IS_FAVORITE, - } -``` -**描述:** -内联函数指针数组AVPlaybackState,用于分布式业务,设置播放界面信息。 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md deleted file mode 100644 index 342eada497e7763e0364121dd6feece15889fa08..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md +++ /dev/null @@ -1,346 +0,0 @@ -# OHOS::AVSession::AVSession - - -## 概述 - -会话对象,支持配置会话属性,并可主动更新播放状态和会话元数据。 - - -## 汇总 - - -### Public 类型 - - | 名称 | 描述 | -| -------- | -------- | -| { **SESSION_TYPE_INVALID** = -1, **SESSION_TYPE_AUDIO** = 0, **SESSION_TYPE_VIDEO** = 1 } | 会话类型的枚举。 | - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [GetSessionId](#getsessionid) ()=0 | 获取会话的标识。 | -| [GetAVMetaData](#getavmetadata) ([AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md) &meta)=0 | 获取会话元数据。 | -| [SetAVMetaData](#setavmetadata) (const [AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md) &meta)=0 | 设置会话元数据。 | -| [GetAVPlaybackState](#getavplaybackstate) ([AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md) &state)=0 | 获取音视频的播放状态。 | -| [SetAVPlaybackState](#setavplaybackstate) (const [AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md) &state)=0 | 设置音视频的播放状态。 | -| [SetLaunchAbility](#setlaunchability) (const AbilityRuntime::WantAgent::WantAgent &ability)=0 | 设置一个WantAgent用于启动会话的Ability。 | -| [GetController](#getcontroller) ()=0 | 获取会话控制器。 | -| [RegisterCallback](#registercallback) (const std::shared_ptr< [AVSessionCallback](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_callback.md) > &callback)=0 | 注册会话回调。 | -| [Activate](#activate) ()=0 | 激活会话。 | -| [Deactivate](#deactivate) ()=0 | 去激活会话。 | -| [IsActive](#isactive) ()=0 | 获取会话是否被激活。 | -| [Destroy](#destroy) ()=0 | 销毁会话。 | -| [AddSupportCommand](#addsupportcommand) (const int32_t cmd)=0 | 添加支持的控制命令。 | -| [DeleteSupportCommand](#deletesupportcommand) (const int32_t cmd)=0 | 删除支持的控制命令。 | - - -## 成员枚举类型说明 - - -### anonymous enum - - -``` -anonymous enum -``` -**描述:** -会话类型的枚举。 - - | 枚举值 | 描述 | -| -------- | -------- | -| SESSION_TYPE_INVALID | 无效会话 | -| SESSION_TYPE_AUDIO | 音频会话 | -| SESSION_TYPE_VIDEO | 视频会话 | - - -## 成员函数说明 - - -### Activate() - - -``` -virtual int32_t OHOS::AVSession::AVSession::Activate () -``` -**描述:** -激活会话。 - -激活成功后,会话才可以接收控制指令。 - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[Deactivate](#deactivate) - -[IsActive](#isactive) - - -### AddSupportCommand() - - -``` -virtual int32_t OHOS::AVSession::AVSession::AddSupportCommand (const int32_t cmd) -``` -**描述:** -添加支持的控制命令。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| cmd | 待添加的控制命令,范围为**SESSION_CMD_INVALID**到**SESSION_CMD_MAX**。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### Deactivate() - - -``` -virtual int32_t OHOS::AVSession::AVSession::Deactivate () -``` -**描述:** -去激活会话。 - -去激活成功后,表示会话还不能接收控制指令。 - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[Activate](#activate) - -[IsActive](#isactive) - - -### DeleteSupportCommand() - - -``` -virtual int32_t OHOS::AVSession::AVSession::DeleteSupportCommand (const int32_t cmd) -``` -**描述:** -删除支持的控制命令。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| cmd | 待删除的控制命令,范围为**SESSION_CMD_INVALID**到**SESSION_CMD_MAX**。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### Destroy() - - -``` -virtual int32_t OHOS::AVSession::AVSession::Destroy () -``` -**描述:** -销毁会话。 - -如果应用要创建一个新会话,必须要销毁之前的会话,否则会创建失败。 - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### GetAVMetaData() - - -``` -virtual int32_t OHOS::AVSession::AVSession::GetAVMetaData (AVMetaData & meta) -``` -**描述:** -获取会话元数据。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| meta | 用于保存会话的元数据[AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md)对象。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[SetAVMetaData](#setavmetadata) - - -### GetAVPlaybackState() - - -``` -virtual int32_t OHOS::AVSession::AVSession::GetAVPlaybackState (AVPlaybackState & state) -``` -**描述:** -获取音视频的播放状态。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| state | 用于保存播放状态的[AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md)对象。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[SetAVPlaybackState](#setavplaybackstate) - - -### GetController() - - -``` -virtual std::shared_ptr OHOS::AVSession::AVSession::GetController () -``` -**描述:** -获取会话控制器。 - -**返回:** - -返回会话控制器,[AVSessionController](o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md)类型智能指针。 - - -### GetSessionId() - - -``` -virtual std::string OHOS::AVSession::AVSession::GetSessionId () -``` -**描述:** -获取会话的标识。 - -**返回:** - -返回会话的标识。 - - -### IsActive() - - -``` -virtual bool OHOS::AVSession::AVSession::IsActive () -``` -**描述:** -获取会话是否被激活。 - -**返回:** - -如果是激活状态,则返回true;否则返回false。 - -**参见:** - -[Activate](#activate) - -[Deactivate](#deactivate) - - -### RegisterCallback() - - -``` -virtual int32_t OHOS::AVSession::AVSession::RegisterCallback (const std::shared_ptr< AVSessionCallback > & callback) -``` -**描述:** -注册会话回调。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| callback | 用于注册会话回调的[AVSessionCallback](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_callback.md)对象。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### SetAVMetaData() - - -``` -virtual int32_t OHOS::AVSession::AVSession::SetAVMetaData (const AVMetaData & meta) -``` -**描述:** -设置会话元数据。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| meta | 用于修改会话的元数据[AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md)对象。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[GetAVMetaData](#getavmetadata) - - -### SetAVPlaybackState() - - -``` -virtual int32_t OHOS::AVSession::AVSession::SetAVPlaybackState (const AVPlaybackState & state) -``` -**描述:** -设置音视频的播放状态。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| state | 用于修改播放状态的[AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md)对象。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[GetAVPlaybackState](#getavplaybackstate) - - -### SetLaunchAbility() - - -``` -virtual int32_t OHOS::AVSession::AVSession::SetLaunchAbility (const AbilityRuntime::WantAgent::WantAgent & ability) -``` -**描述:** -设置一个WantAgent用于启动会话的Ability。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| ability | 具体的应用对应的能力,类型为**AbilityRuntime::WantAgent::WantAgent**。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[AVSessionController::GetLaunchAbility](o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md#getlaunchability) diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_callback.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_callback.md deleted file mode 100644 index f29d9b05ccac47581821d2a3df2a31e1539c73f5..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_callback.md +++ /dev/null @@ -1,215 +0,0 @@ -# OHOS::AVSession::AVSessionCallback - - -## 概述 - -定义AVSession回调类的实现 - -**起始版本:** -9 - -## 汇总 - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [OnPlay](#onplay) ()=0 | AVSession多媒体播放的抽象的回调方法。 | -| [OnPause](#onpause) ()=0 | AVSession多媒体播放暂停的抽象的回调方法。 | -| [OnStop](#onstop) ()=0 | AVSession多媒体播放停止的抽象的回调方法。 | -| [OnPlayNext](#onplaynext) ()=0 | AVSession播放下一首多媒体的抽象的回调方法。 | -| [OnPlayPrevious](#onplayprevious) ()=0 | AVSession播放上一首多媒体的抽象的回调方法。 | -| [OnFastForward](#onfastforward) ()=0 | AVSession快进播放多媒体的抽象的回调方法。 | -| [OnRewind](#onrewind) ()=0 | AVSession多媒体快退的抽象的回调方法。 | -| [OnSeek](#onseek) (int64_t time)=0 | AVSession多媒体跳播操作的抽象的回调方法。 | -| [OnSetSpeed](#onsetspeed) (double speed)=0 | AVSession设置多媒体倍速播放操作的抽象的回调方法。 | -| [OnSetLoopMode](#onsetloopmode) (int32_t loopMode)=0 | AVSession设置多媒体循环播放模式的抽象的回调方法。 | -| [OnToggleFavorite](#ontogglefavorite) (const std::string &mediald)=0 | AVSession设置多媒体切换收藏操作的抽象的回调方法。 | -| [OnMediaKeyEvent](#onmediakeyevent) (const MMI::KeyEvent &keyEvent)=0 | AVSession多媒体按键事件处理的抽象的回调方法。 | -| [OnOutputDeviceChange](#onoutputdevicechange) (const [OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md) &outputDeviceInfo)=0 | 注册会话输出设备变更监听。 | -| [~AVSessionCallback](#avsessioncallback) ()=default | AVSessionCallback的默认的析构函数。 | - - -## 构造及析构函数说明 - - -### ~AVSessionCallback() - - -``` -virtual OHOS::AVSession::AVSessionCallback::~AVSessionCallback () -``` -**描述:** -AVSessionCallback的默认的析构函数。 - - -## 成员函数说明 - - -### OnFastForward() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnFastForward () -``` -**描述:** -AVSession快进播放多媒体的抽象的回调方法。 - - -### OnMediaKeyEvent() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnMediaKeyEvent (const MMI::KeyEvent & keyEvent) -``` -**描述:** -AVSession多媒体按键事件处理的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| keyEvent | 按键事件码,类型为**MMI::KeyEvent**。 | - - -### OnOutputDeviceChange() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnOutputDeviceChange (const OutputDeviceInfo & outputDeviceInfo) -``` -**描述:** -注册会话输出设备变更监听。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| outputDeviceInfo | 输出设备信息 [OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md)。 | - - -### OnPause() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnPause () -``` -**描述:** -AVSession多媒体播放暂停的抽象的回调方法。 - - -### OnPlay() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnPlay () -``` -**描述:** -AVSession多媒体播放的抽象的回调方法。 - - -### OnPlayNext() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnPlayNext () -``` -**描述:** -AVSession播放下一首多媒体的抽象的回调方法。 - - -### OnPlayPrevious() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnPlayPrevious () -``` -**描述:** -AVSession播放上一首多媒体的抽象的回调方法。 - - -### OnRewind() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnRewind () -``` -**描述:** -AVSession多媒体快退的抽象的回调方法。 - - -### OnSeek() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnSeek (int64_t time) -``` -**描述:** -AVSession多媒体跳播操作的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| time | 媒体资源的位置,从媒体资源开头开始计算,单位为ms。取值需大于等于0。 | - - -### OnSetLoopMode() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnSetLoopMode (int32_t loopMode) -``` -**描述:** -AVSession设置多媒体循环播放模式的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| loopMode | 多媒体循环播放模式, 范围在[AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md)的**LOOP_MODE_SEQUENCE**到**LOOP_MODE_SHUFFLE**之间。 | - - -### OnSetSpeed() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnSetSpeed (double speed) -``` -**描述:** -AVSession设置多媒体倍速播放操作的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| speed | 多媒体播放的倍速值。 | - - -### OnStop() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnStop () -``` -**描述:** -AVSession多媒体播放停止的抽象的回调方法。 - - -### OnToggleFavorite() - - -``` -virtual void OHOS::AVSession::AVSessionCallback::OnToggleFavorite (const std::string & mediald) -``` -**描述:** -AVSession设置多媒体切换收藏操作的抽象的回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| mediald | 多媒体ID号标识。 | - - diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_manager.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_manager.md deleted file mode 100644 index 1b6f5216da599120e71d5f906623c6de38e086c6..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_manager.md +++ /dev/null @@ -1,300 +0,0 @@ -# OHOS::AVSession::AVSessionManager - - -## 概述 - -实现会话管理器对外接口功能的类的实现。 - -**起始版本:** -9 - -## 汇总 - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [CreateSession](#createsession) (const std::string &tag, int32_t type, const AppExecFwk::ElementName &elementName)=0 | 创建AVSession会话的接口方法。 | -| [GetAllSessionDescriptors](#getallsessiondescriptors) (std::vector< [AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) > &descriptors)=0 | 获取AVSession全部的会话描述的接口方法。 | -| [GetActivatedSessionDescriptors](#getactivatedsessiondescriptors) (std::vector< [AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) > &activatedSessions)=0 | 获取AVSession全部处于活动状态的会话描述的接口方法。 | -| [GetSessionDescriptorsBySessionId](#getsessiondescriptorsbysessionid) (const std::string &sessionId, [AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) &descriptor)=0 | 通过会话ID获得会话描述的方法。 | -| [CreateController](#createcontroller) (const std::string &sessionId, std::shared_ptr< [AVSessionController](o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md) > &controller)=0 | 创建AVSession会话控制器的接口方法。 | -| [RegisterSessionListener](#registersessionlistener) (const std::shared_ptr< [SessionListener](_o_h_o_s_1_1_a_v_session_1_1_session_listener.md) > &listener)=0 | 注册AVSession会话监听器的接口方法。 | -| [RegisterServiceDeathCallback](#registerservicedeathcallback) (const [DeathCallback](avsession__info_8h.md#deathcallback) &callback)=0 | 注册AVSession服务器的死亡回调的接口方法。 | -| [UnregisterServiceDeathCallback](#unregisterservicedeathcallback) ()=0 | 注销AVSession服务器的死亡回调的接口方法。 | -| [SendSystemAVKeyEvent](#sendsystemavkeyevent) (const MMI::KeyEvent &keyEvent)=0 | 发送系统按键事件的接口方法。 | -| [SendSystemControlCommand](#sendsystemcontrolcommand) (const [AVControlCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md) &command)=0 | 发送系统控制命令的接口方法。 | -| [CastAudio](#castaudio) (const [SessionToken](_o_h_o_s_1_1_a_v_session_1_1_session_token.md) &token, const std::vector< AudioStandard::AudioDeviceDescriptor > &descriptors)=0 | 将媒体会话投射到远程设备或投射回本地设备。 | -| [CastAudioForAll](#castaudioforall) (const std::vector< AudioStandard::AudioDeviceDescriptor > &descriptors)=0 | 将此设备的所有媒体会话投播到远程设备。 | - - -### 静态 Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [GetInstance](#getinstance) () | 获取会话管理器实例。 | - - -## 成员函数说明 - - -### CastAudio() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::CastAudio (const SessionToken & token, const std::vector< AudioStandard::AudioDeviceDescriptor > & descriptors ) -``` -**描述:** -将媒体会话投射到远程设备或投射回本地设备。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| token | 需要投播的会话令牌。 | -| descriptors | 指定要转换的音频设备。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### CastAudioForAll() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::CastAudioForAll (const std::vector< AudioStandard::AudioDeviceDescriptor > & descriptors) -``` -**描述:** -将此设备的所有媒体会话投播到远程设备。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| descriptors | 指定要转换的音频设备。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### CreateController() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::CreateController (const std::string & sessionId, std::shared_ptr< AVSessionController > & controller ) -``` -**描述:** -创建AVSession会话控制器的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| sessionId | AVSession的会话ID。 | -| controller | 会话控制器实例,类型为[AVSessionController](o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md)。 | - -**返回:** - -返回成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### CreateSession() - - -``` -virtual std::shared_ptr OHOS::AVSession::AVSessionManager::CreateSession (const std::string & tag, int32_t type, const AppExecFwk::ElementName & elementName ) -``` -**描述:** -创建AVSession会话的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| tag | AVSession的会话标签,不可为空。 | -| type | AVSession的会话类型, 入参为[AVSession](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md)的**SESSION_TYPE_AUDIO**,**SESSION_TYPE_VIDEO**。 | -| elementName | AVSession的会话名称**AppExecFwk::ElementName**。 | - -**返回:** - -返回已创建的会话对象的智能指针。 - - -### GetActivatedSessionDescriptors() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::GetActivatedSessionDescriptors (std::vector< AVSessionDescriptor > & activatedSessions) -``` -**描述:** -获取AVSession全部处于活动状态的会话描述的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| activatedSessions | 处于活动状态的会话描述,类型为[AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md)。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### GetAllSessionDescriptors() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::GetAllSessionDescriptors (std::vector< AVSessionDescriptor > & descriptors) -``` -**描述:** -获取AVSession全部的会话描述的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| descriptors | AVSession的会话描述,类型为[AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md)。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### GetInstance() - - -``` -static AVSessionManager& OHOS::AVSession::AVSessionManager::GetInstance () -``` -**描述:** -获取会话管理器实例。 - -**返回:** - -返回会话管理器实例。 - - -### GetSessionDescriptorsBySessionId() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::GetSessionDescriptorsBySessionId (const std::string & sessionId, AVSessionDescriptor & descriptor ) -``` -**描述:** -通过会话ID获得会话描述的方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| sessionId | AVSession的会话标签。 | -| descriptor | AVSession的会话描述,类型为[AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md)。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### RegisterServiceDeathCallback() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::RegisterServiceDeathCallback (const DeathCallback & callback) -``` -**描述:** -注册AVSession服务器的死亡回调的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| callback | 死亡回调的方法,类型为**DeathCallback**。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[UnregisterServiceDeathCallback](#unregisterservicedeathcallback) - - -### RegisterSessionListener() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::RegisterSessionListener (const std::shared_ptr< SessionListener > & listener) -``` -**描述:** -注册AVSession会话监听器的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| listener | 会话监听器的智能指针,类型为[SessionListener](_o_h_o_s_1_1_a_v_session_1_1_session_listener.md)。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### SendSystemAVKeyEvent() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::SendSystemAVKeyEvent (const MMI::KeyEvent & keyEvent) -``` -**描述:** -发送系统按键事件的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| keyEvent | 按键事件码,类型为**MMI::KeyEvent**。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### SendSystemControlCommand() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::SendSystemControlCommand (const AVControlCommand & command) -``` -**描述:** -发送系统控制命令的接口方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| command | 系统控制命令[AVControlCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md)。 | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### UnregisterServiceDeathCallback() - - -``` -virtual int32_t OHOS::AVSession::AVSessionManager::UnregisterServiceDeathCallback () -``` -**描述:** -注销AVSession服务器的死亡回调的接口方法。 - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[RegisterServiceDeathCallback](#registerservicedeathcallback) diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md deleted file mode 100644 index 39038f5b3f40ec407e99d33b60d2f7cd27113aae..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md +++ /dev/null @@ -1,154 +0,0 @@ -# OHOS::AVSession::AVSessionPixelMap - - -## 概述 - -读取、设置图片及图片信息。 - - -## 汇总 - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [Marshalling](#marshalling) (Parcel &data) const override | 实现图片及图片信息的序列化。  | -| [GetPixelData](#getpixeldata) () const | 获取图片数据。  | -| [SetPixelData](#setpixeldata) (const std::vector< uint8_t > &data) | 设置图片数据。  | -| [GetImageInfo](#getimageinfo) () const | 获取图片信息。  | -| [SetImageInfo](#setimageinfo) (const std::vector< uint8_t > &imageInfo) | 设置图片信息。  | - - -### 静态 Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [Unmarshalling](#unmarshalling) (Parcel &data) | 实现图片及图片信息的反序列化。  | - - -## 成员函数说明 - - -### GetImageInfo() - - -``` -std::vector OHOS::AVSession::AVSessionPixelMap::GetImageInfo () const -``` -**描述:** -获取图片信息。 - -**返回:** - -返回图片信息。 - -**参见:** - -[SetImageInfo](#setimageinfo) - - -### GetPixelData() - - -``` -std::vector OHOS::AVSession::AVSessionPixelMap::GetPixelData () const -``` -**描述:** -获取图片数据。 - -**返回:** - -返回图片数据。 - -**参见:** - -[SetPixelData](#setpixeldata) - - -### Marshalling() - - -``` -bool OHOS::AVSession::AVSessionPixelMap::Marshalling (Parcel & data) const -``` -**描述:** -实现图片及图片信息的序列化。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 保存序列化值的对象**Parcel**。  | - -**返回:** - -如果序列化成功,则返回true;失败则返回false。 - -**参见:** - -[Unmarshalling](#unmarshalling) - - -### SetImageInfo() - - -``` -void OHOS::AVSession::AVSessionPixelMap::SetImageInfo (const std::vector< uint8_t > & imageInfo) -``` -**描述:** -设置图片信息。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| imageInfo | 图片信息。  | - -**参见:** - -[GetImageInfo](#getimageinfo) - - -### SetPixelData() - - -``` -void OHOS::AVSession::AVSessionPixelMap::SetPixelData (const std::vector< uint8_t > & data) -``` -**描述:** -设置图片数据。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 图片数据。  | - -**参见:** - -[GetPixelData](#getpixeldata) - - -### Unmarshalling() - - -``` -static AVSessionPixelMap* OHOS::AVSession::AVSessionPixelMap::Unmarshalling (Parcel & data) -``` -**描述:** -实现图片及图片信息的反序列化。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 保存反序列化值的对象**Parcel**。  | - -**返回:** - -如果反序列化成功,则返回true;失败则返回false。 - -**参见:** - -[Marshalling](#marshalling) diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md deleted file mode 100644 index f1aa54fa9b1c1cbdfa2b11c8784c1a57f39cd858..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md +++ /dev/null @@ -1,25 +0,0 @@ -# OHOS::AVSession::OutputDeviceInfo - - -## 概述 - -描述分布式设备的相关信息。 - -**起始版本:** -9 - -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 成员变量 - - | 名称 | 描述 | -| -------- | -------- | -| [isRemote_](avsession.md#isremote) {} | bool | -| [deviceIds_](avsession.md#deviceids) | std::vector< std::string > | -| [deviceNames_](avsession.md#devicenames) | std::vector< std::string > | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_session_listener.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_session_listener.md deleted file mode 100644 index f4d8988dc3c18cd766cc620d959a030ad713fcc8..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_session_listener.md +++ /dev/null @@ -1,95 +0,0 @@ -# OHOS::AVSession::SessionListener - - -## 概述 - -定义与AVSession相关监听器的类的实现。 - -**起始版本:** -9 - -## 汇总 - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [OnSessionCreate](#onsessioncreate) (const [AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) &descriptor)=0 | 创建AVSession会话的抽象的接口回调方法。  | -| [OnSessionRelease](#onsessionrelease) (const [AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) &descriptor)=0 | 释放AVSession会话的抽象的接口回调方法。  | -| [OnTopSessionChange](#ontopsessionchange) (const [AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) &descriptor)=0 | AVSession的TOP会话发生变化的抽象的接口回调方法。  | -| [~SessionListener](#sessionlistener) ()=default | SessionListener的默认的析构函数。  | - - -## 构造及析构函数说明 - - -### ~SessionListener() - - -``` -virtual OHOS::AVSession::SessionListener::~SessionListener () -``` -**描述:** -SessionListener的默认的析构函数。 - - -## 成员函数说明 - - -### OnSessionCreate() - - -``` -virtual void OHOS::AVSession::SessionListener::OnSessionCreate (const AVSessionDescriptor & descriptor) -``` -**描述:** -创建AVSession会话的抽象的接口回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| descriptor | AVSession的会话描述对象,类型为[AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md)。  | - -**参见:** - -[OnSessionRelease](#onsessionrelease) - - -### OnSessionRelease() - - -``` -virtual void OHOS::AVSession::SessionListener::OnSessionRelease (const AVSessionDescriptor & descriptor) -``` -**描述:** -释放AVSession会话的抽象的接口回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| descriptor | AVSession的会话描述对象,类型为[AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md)。  | - -**参见:** - -[OnSessionCreate](#onsessioncreate) - - -### OnTopSessionChange() - - -``` -virtual void OHOS::AVSession::SessionListener::OnTopSessionChange (const AVSessionDescriptor & descriptor) -``` -**描述:** -AVSession的TOP会话发生变化的抽象的接口回调方法。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| descriptor | AVSession的会话描述对象,类型为[AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md)。  | - - \ No newline at end of file diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_session_token.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_session_token.md deleted file mode 100644 index 66fe6a463ad9f777da6702d8be1081f9769608ed..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_a_v_session_1_1_session_token.md +++ /dev/null @@ -1,53 +0,0 @@ -# OHOS::AVSession::SessionToken - - -## 概述 - -会话令牌的信息。 - -**起始版本:** -9 - -## 汇总 - - -### 成员变量 - - | 名称 | 描述 | -| -------- | -------- | -| [sessionId](#sessionid) | std::string
会话id  | -| [pid](#pid) | pid_t
会话的进程id  | -| [uid](#uid) | uid_t
用户id  | - - -## 结构体成员变量说明 - - -### pid - - -``` -pid_t OHOS::AVSession::SessionToken::pid -``` -**描述:** -会话的进程id - - -### sessionId - - -``` -std::string OHOS::AVSession::SessionToken::sessionId -``` -**描述:** -会话id - - -### uid - - -``` -uid_t OHOS::AVSession::SessionToken::uid -``` -**描述:** -用户id diff --git a/zh-cn/application-dev/reference/native-apis/av__session_8h.md b/zh-cn/application-dev/reference/native-apis/av__session_8h.md deleted file mode 100644 index d66bfd2434a958ece2a0171b06a6e3c5ba1a51aa..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/av__session_8h.md +++ /dev/null @@ -1,24 +0,0 @@ -# av_session.h - - -## 概述 - -会话的设置、获取等声明。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVSession](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md) | class
会话对象,支持配置会话属性,并可主动更新播放状态和会话元数据。 | diff --git a/zh-cn/application-dev/reference/native-apis/avcontrol__command_8h.md b/zh-cn/application-dev/reference/native-apis/avcontrol__command_8h.md deleted file mode 100644 index 4cc45e90195352c11b2722f781b4476bcf83ea65..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avcontrol__command_8h.md +++ /dev/null @@ -1,24 +0,0 @@ -# avcontrol_command.h - - -## 概述 - -音视频控制指令的设置、获取、拷贝等声明。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVControlCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md) | class
用于描述音视频播控命令工具类,播控命令的封装对象,支持设置和获取控制命令。 | diff --git a/zh-cn/application-dev/reference/native-apis/avmeta__data_8h.md b/zh-cn/application-dev/reference/native-apis/avmeta__data_8h.md deleted file mode 100644 index bbaa050e9c59a64eb3fd0c30067e4cc7be2c80bb..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avmeta__data_8h.md +++ /dev/null @@ -1,24 +0,0 @@ -# avmeta_data.h - - -## 概述 - -会话元数据设置、获取、拷贝等接口声明。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md) | class
会话元数据类,提供获取metadata进程间传递的序列化和反序列话及数据拷贝的接口方法。 | diff --git a/zh-cn/application-dev/reference/native-apis/avplayback__state_8h.md b/zh-cn/application-dev/reference/native-apis/avplayback__state_8h.md deleted file mode 100644 index d8099b9ab12636559ebab1aae8630eb9f6d1b711..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avplayback__state_8h.md +++ /dev/null @@ -1,25 +0,0 @@ -# avplayback_state.h - - -## 概述 - -音视频播放状态声明。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md) | class
音视频播放状态类,提供获取和设置播放界面的信息。 | -| [OHOS::AVSession::AVPlaybackState::Position](_1_a_v_session_1_1_a_v_playback_state_1_1_position.md) | struct
播放位置的相关信息。 | diff --git a/zh-cn/application-dev/reference/native-apis/avsession.md b/zh-cn/application-dev/reference/native-apis/avsession.md deleted file mode 100644 index 95409373aa19c84cd89fd64f50237a0a5764d81d..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avsession.md +++ /dev/null @@ -1,469 +0,0 @@ -# Avsession - - -## 概述 - -音视频媒体会话,提供系统内媒体的统一控制能力。 - -功能包括媒体会话,媒体会话管理,媒体会话控制。 - -@syscap SystemCapability.Multimedia.AVSession.Core - -**起始版本:** - -9 - -**Version:** - -1.0 - - -## 汇总 - - -### 文件 - - | 名称 | 描述 | -| -------- | -------- | -| [av_session.h](av__session_8h.md) | 会话的设置、获取等声明。 | -| [avcontrol_command.h](avcontrol__command_8h.md) | 音视频控制指令的设置、获取、拷贝等声明。 | -| [avmeta_data.h](avmeta__data_8h.md) | 会话元数据设置、获取、拷贝等接口声明。 | -| [avplayback_state.h](avplayback__state_8h.md) | 音视频播放状态声明。 | -| [avsession_controller.h](avsession__controller_8h.md) | 控制器对象的描述,可获取会话的播放状态和会话元数据,远程发送控制命令到会话端也可以通过订阅监听会话段的更新事件。 | -| [avsession_descriptor.h](avsession__descriptor_8h.md) | 会话的相关描述信息。 | -| [avsession_errors.h](avsession__errors_8h.md) | 定义了avsession错误码。 | -| [avsession_info.h](avsession__info_8h.md) | 定义了与avsession相关的监听器以及回调功能的实现。 | -| [avsession_manager.h](avsession__manager_8h.md) | 定义了会话管理器对外接口的功能的实现。 | -| [avsession_pixel_map.h](avsession__pixel__map_8h.md) | 读取、设置图片及图片信息。 | - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md) | struct
描述分布式设备的相关信息。 | -| [OHOS::AVSession::AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) | struct
会话的相关描述信息。 | -| [OHOS::AVSession::AVSessionBasicInfo](o_h_o_s_1_1_a_v_session_1_1_a_v_session_basic_info.md) | struct
会话基础信息描述。 | - - -### 函数 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVSessionDescriptor::WriteToParcel](#writetoparcel) (Parcel &out) const | bool
将会话相关描述信息写进包里。 | -| [OHOS::AVSession::AVSessionDescriptor::ReadFromParcel](#readfromparcel) (Parcel &in) | bool
对会话相关描述信息进行解包。 | - - -### 变量 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::OutputDeviceInfo::isRemote_](#isremote) {} | bool
是否连接 | -| [OHOS::AVSession::OutputDeviceInfo::deviceIds_](#deviceids) | std::vector< std::string >
分布式设备的id集合 | -| [OHOS::AVSession::OutputDeviceInfo::deviceNames_](#devicenames) | std::vector< std::string >
分布式设备的名称集合 | -| [OHOS::AVSession::AVSessionDescriptor::sessionId_](#sessionid) | std::string
会话的id | -| [OHOS::AVSession::AVSessionDescriptor::sessionType_](#sessiontype) {} | int32_t
会话的类型 | -| [OHOS::AVSession::AVSessionDescriptor::sessionTag_](#sessiontag) | std::string
会话的自定义名称 | -| [OHOS::AVSession::AVSessionDescriptor::elementName_](#elementname) | AppExecFwk::ElementName
会话所属应用的信息包含bundleName,abilityName等 | -| [OHOS::AVSession::AVSessionDescriptor::pid_](#pid) {} | pid_t
进程id | -| [OHOS::AVSession::AVSessionDescriptor::uid_](#uid) {} | pid_t
用户id | -| [OHOS::AVSession::AVSessionDescriptor::isActive_](#isactive) {} | bool
会话是否为激活状态 | -| [OHOS::AVSession::AVSessionDescriptor::isTopSession_](#istopsession) {} | bool
会话是否是最新的会话 | -| [OHOS::AVSession::AVSessionDescriptor::isThirdPartyApp_](#isthirdpartyapp) {} | bool
是否是第三方应用 | -| [OHOS::AVSession::AVSessionDescriptor::outputDeviceInfo_](#outputdeviceinfo) | [OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md)
分布式设备相关信息 | -| [OHOS::AVSession::AVSessionBasicInfo::deviceName_](#devicename) {} | std::string
设备名称 | -| [OHOS::AVSession::AVSessionBasicInfo::networkId_](#networkid) {} | std::string
设备id | -| [OHOS::AVSession::AVSessionBasicInfo::vendorId_](#vendorid) {} | std::string
供应商id | -| [OHOS::AVSession::AVSessionBasicInfo::deviceType_](#devicetype) {} | std::string
设备类型 | -| [OHOS::AVSession::AVSessionBasicInfo::systemVersion_](#systemversion) {} | std::string
系统版本 | -| [OHOS::AVSession::AVSessionBasicInfo::sessionVersion_](#sessionversion) {} | int32_t
会话版本 | -| [OHOS::AVSession::AVSessionBasicInfo::reserve_](#reserve) {} | std::vector< int32_t >
备注信息 | -| [OHOS::AVSession::AVSessionBasicInfo::feature_](#feature) {} | std::vector< int32_t >
特征信息 | -| [OHOS::AVSession::AVSessionBasicInfo::metaDataCap_](#metadatacap) {} | std::vector< int32_t >
会话元数据 | -| [OHOS::AVSession::AVSessionBasicInfo::playBackStateCap_](#playbackstatecap) {} | std::vector< int32_t >
支持播放状态数组 | -| [OHOS::AVSession::AVSessionBasicInfo::controlCommandCap_](#controlcommandcap) {} | std::vector< int32_t >
系统控制命令 | -| [OHOS::AVSession::AVSessionBasicInfo::extendCapability_](#extendcapability) {} | std::vector< int32_t >
扩展能力 | -| [OHOS::AVSession::AVSessionBasicInfo::systemTime_](#systemtime) {} | int32_t
系统时间 | -| [OHOS::AVSession::AVSessionBasicInfo::extend_](#extend) {} | std::vector< int32_t >
扩展信息 | - - -## 函数说明 - - -### ReadFromParcel() - - -``` -bool OHOS::AVSession::AVSessionDescriptor::ReadFromParcel (Parcel & in) -``` - -**描述:** - -对会话相关描述信息进行解包。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| in | 读出的会话相关描述信息对象**Parcel**。 | - -**返回:** - -成功返回true;失败则返回false。 - -**参见:** - -[WriteToParcel](#writetoparcel) - - -### WriteToParcel() - - -``` -bool OHOS::AVSession::AVSessionDescriptor::WriteToParcel (Parcel & out) const -``` - -**描述:** - -将会话相关描述信息写进包里。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| out | 写入的会话相关描述信息对象**Parcel**。 | - -**返回:** - -成功返回true;失败则返回false。 - -**参见:** - -[ReadFromParcel](#readfromparcel) - - -## 变量说明 - - -### controlCommandCap_ - - -``` -std::vector OHOS::AVSession::AVSessionBasicInfo::controlCommandCap_ {} -``` - -**描述:** - -系统控制命令 - - -### deviceIds_ - - -``` -std::vector OHOS::AVSession::OutputDeviceInfo::deviceIds_ -``` - -**描述:** - -分布式设备的id集合 - - -### deviceName_ - - -``` -std::string OHOS::AVSession::AVSessionBasicInfo::deviceName_ {} -``` - -**描述:** - -设备名称 - - -### deviceNames_ - - -``` -std::vector OHOS::AVSession::OutputDeviceInfo::deviceNames_ -``` - -**描述:** - -分布式设备的名称集合 - - -### deviceType_ - - -``` -std::string OHOS::AVSession::AVSessionBasicInfo::deviceType_ {} -``` - -**描述:** - -设备类型 - - -### elementName_ - - -``` -AppExecFwk::ElementName OHOS::AVSession::AVSessionDescriptor::elementName_ -``` - -**描述:** - -会话所属应用的信息包含bundleName,abilityName等 - - -### extend_ - - -``` -std::vector OHOS::AVSession::AVSessionBasicInfo::extend_ {} -``` - -**描述:** - -扩展信息 - - -### extendCapability_ - - -``` -std::vector OHOS::AVSession::AVSessionBasicInfo::extendCapability_ {} -``` - -**描述:** - -扩展能力 - - -### feature_ - - -``` -std::vector OHOS::AVSession::AVSessionBasicInfo::feature_ {} -``` - -**描述:** - -特征信息 - - -### isActive_ - - -``` -bool OHOS::AVSession::AVSessionDescriptor::isActive_ {} -``` - -**描述:** - -会话是否为激活状态 - - -### isRemote_ - - -``` -bool OHOS::AVSession::OutputDeviceInfo::isRemote_ {} -``` - -**描述:** - -是否连接 - - -### isThirdPartyApp_ - - -``` -bool OHOS::AVSession::AVSessionDescriptor::isThirdPartyApp_ {} -``` - -**描述:** - -是否是第三方应用 - - -### isTopSession_ - - -``` -bool OHOS::AVSession::AVSessionDescriptor::isTopSession_ {} -``` - -**描述:** - -会话是否是最新的会话 - - -### metaDataCap_ - - -``` -std::vector OHOS::AVSession::AVSessionBasicInfo::metaDataCap_ {} -``` - -**描述:** - -会话元数据 - - -### networkId_ - - -``` -std::string OHOS::AVSession::AVSessionBasicInfo::networkId_ {} -``` - -**描述:** - -设备id - - -### outputDeviceInfo_ - - -``` -OutputDeviceInfo OHOS::AVSession::AVSessionDescriptor::outputDeviceInfo_ -``` - -**描述:** - -分布式设备相关信息 - - -### pid_ - - -``` -pid_t OHOS::AVSession::AVSessionDescriptor::pid_ {} -``` - -**描述:** - -进程id - - -### playBackStateCap_ - - -``` -std::vector OHOS::AVSession::AVSessionBasicInfo::playBackStateCap_ {} -``` - -**描述:** - -支持播放状态数组 - - -### reserve_ - - -``` -std::vector OHOS::AVSession::AVSessionBasicInfo::reserve_ {} -``` - -**描述:** - -备注信息 - - -### sessionId_ - - -``` -std::string OHOS::AVSession::AVSessionDescriptor::sessionId_ -``` - -**描述:** - -会话的id - - -### sessionTag_ - - -``` -std::string OHOS::AVSession::AVSessionDescriptor::sessionTag_ -``` - -**描述:** - -会话的自定义名称 - - -### sessionType_ - - -``` -int32_t OHOS::AVSession::AVSessionDescriptor::sessionType_ {} -``` - -**描述:** - -会话的类型 - - -### sessionVersion_ - - -``` -int32_t OHOS::AVSession::AVSessionBasicInfo::sessionVersion_ {} -``` - -**描述:** - -会话版本 - - -### systemTime_ - - -``` -int32_t OHOS::AVSession::AVSessionBasicInfo::systemTime_ {} -``` - -**描述:** - -系统时间 - - -### systemVersion_ - - -``` -std::string OHOS::AVSession::AVSessionBasicInfo::systemVersion_ {} -``` - -**描述:** - -系统版本 - - -### uid_ - - -``` -pid_t OHOS::AVSession::AVSessionDescriptor::uid_ {} -``` - -**描述:** - -用户id - - -### vendorId_ - - -``` -std::string OHOS::AVSession::AVSessionBasicInfo::vendorId_ {} -``` - -**描述:** - -供应商id diff --git a/zh-cn/application-dev/reference/native-apis/avsession__controller_8h.md b/zh-cn/application-dev/reference/native-apis/avsession__controller_8h.md deleted file mode 100644 index 38446db715f86441463b6268a9edbaa1ae63513f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avsession__controller_8h.md +++ /dev/null @@ -1,24 +0,0 @@ -# avsession_controller.h - - -## 概述 - -控制器对象的描述,可获取会话的播放状态和会话元数据,远程发送控制命令到会话端也可以通过订阅监听会话段的更新事件。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVSessionController](o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md) | class
控制器对象,可获取会话的播放状态和会话元数据,远程发送控制命令到会话端也可以通过订阅监听会话段的更新事件。 | diff --git a/zh-cn/application-dev/reference/native-apis/avsession__descriptor_8h.md b/zh-cn/application-dev/reference/native-apis/avsession__descriptor_8h.md deleted file mode 100644 index 73c87d3892d2ed4e725e9121a1ae33e7c9425884..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avsession__descriptor_8h.md +++ /dev/null @@ -1,26 +0,0 @@ -# avsession_descriptor.h - - -## 概述 - -会话的相关描述信息。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md) | struct
描述分布式设备的相关信息。 | -| [OHOS::AVSession::AVSessionDescriptor](o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md) | struct
会话的相关描述信息。 | -| [OHOS::AVSession::AVSessionBasicInfo](o_h_o_s_1_1_a_v_session_1_1_a_v_session_basic_info.md) | struct
会话基础信息描述。 | diff --git a/zh-cn/application-dev/reference/native-apis/avsession__errors_8h.md b/zh-cn/application-dev/reference/native-apis/avsession__errors_8h.md deleted file mode 100644 index 649a7edbf861e84e6f78714537e881085549686d..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avsession__errors_8h.md +++ /dev/null @@ -1,268 +0,0 @@ -# avsession_errors.h - - -## 概述 - -定义了avsession错误码。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 变量 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVSESSION_ERROR](#avsession_error) = -1 | constexpr int32_t
存在错误 | -| [OHOS::AVSession::AVSESSION_SUCCESS](#avsession_success) = 0 | constexpr int32_t
操作成功 | -| [OHOS::AVSession::AVSESSION_ERROR_BASE](#avsession_error_base) = 1000 | constexpr int32_t
avsession错误码的基定义 | -| [OHOS::AVSession::ERR_NO_MEMORY](#err_no_memory) = -(AVSESSION_ERROR_BASE + 1) | constexpr int32_t
无可用内存 | -| [OHOS::AVSession::ERR_INVALID_PARAM](#err_invalid_param) = -(AVSESSION_ERROR_BASE + 2) | constexpr int32_t
传递的参数无效 | -| [OHOS::AVSession::ERR_SERVICE_NOT_EXIST](#err_service_not_exist) = -(AVSESSION_ERROR_BASE + 3) | constexpr int32_t
服务不存在 | -| [OHOS::AVSession::ERR_SESSION_LISTENER_EXIST](#err_session_listener_exist) = -(AVSESSION_ERROR_BASE + 4) | constexpr int32_t
Session监听器已存在 | -| [OHOS::AVSession::ERR_MARSHALLING](#err_marshalling) = -(AVSESSION_ERROR_BASE + 5) | constexpr int32_t
数据序列化操作错误 | -| [OHOS::AVSession::ERR_UNMARSHALLING](#err_unmarshalling) = -(AVSESSION_ERROR_BASE + 6) | constexpr int32_t
数据反序列化操作错误 | -| [OHOS::AVSession::ERR_IPC_SEND_REQUEST](#err_ipc_send_request) = -(AVSESSION_ERROR_BASE + 7) | constexpr int32_t
IPC发送数据失败 | -| [OHOS::AVSession::ERR_SESSION_EXCEED_MAX](#err_session_exceed_max) = -(AVSESSION_ERROR_BASE + 8) | constexpr int32_t
超过允许会话最大数量 | -| [OHOS::AVSession::ERR_SESSION_NOT_EXIST](#err_session_not_exist) = -(AVSESSION_ERROR_BASE + 9) | constexpr int32_t
会话不存在 | -| [OHOS::AVSession::ERR_COMMAND_NOT_SUPPORT](#err_command_not_support) = -(AVSESSION_ERROR_BASE + 10) | constexpr int32_t
会话命令不支持 | -| [OHOS::AVSession::ERR_CONTROLLER_NOT_EXIST](#err_controller_not_exist) = -(AVSESSION_ERROR_BASE + 11) | constexpr int32_t
控制器不存在 | -| [OHOS::AVSession::ERR_NO_PERMISSION](#err_no_permission) = -(AVSESSION_ERROR_BASE + 12) | constexpr int32_t
无权限 | -| [OHOS::AVSession::ERR_SESSION_DEACTIVE](#err_session_deactive) = -(AVSESSION_ERROR_BASE + 13) | constexpr int32_t
会话未激活 | -| [OHOS::AVSession::ERR_CONTROLLER_IS_EXIST](#err_controller_is_exist) = -(AVSESSION_ERROR_BASE + 14) | constexpr int32_t
控制器存在 | -| [OHOS::AVSession::ERR_START_ABILITY_IS_RUNNING](#err_start_ability_is_running) = -(AVSESSION_ERROR_BASE + 15) | constexpr int32_t
元能力正在运行 | -| [OHOS::AVSession::ERR_ABILITY_NOT_AVAILABLE](#err_ability_not_available) = -(AVSESSION_ERROR_BASE + 16) | constexpr int32_t
元能力启动超失败 | -| [OHOS::AVSession::ERR_START_ABILITY_TIMEOUT](#err_start_ability_timeout) = -(AVSESSION_ERROR_BASE + 17) | constexpr int32_t
元能力启动超时 | -| [OHOS::AVSession::ERR_COMMAND_SEND_EXCEED_MAX](#err_command_send_exceed_max) = -(AVSESSION_ERROR_BASE + 18) | constexpr int32_t
指令发送次数超过最大值 | -| [OHOS::AVSession::ERR_RPC_SEND_REQUEST](#err_rpc_send_request) = -(AVSESSION_ERROR_BASE + 19) | constexpr int32_t
RPC发送数据失败 | - - -## 变量说明 - - -### AVSESSION_ERROR - - -``` -constexpr int32_t OHOS::AVSession::AVSESSION_ERROR = -1 -``` -**描述:** -存在错误 - - -### AVSESSION_ERROR_BASE - - -``` -constexpr int32_t OHOS::AVSession::AVSESSION_ERROR_BASE = 1000 -``` -**描述:** -avsession错误码的基定义 - - -### AVSESSION_SUCCESS - - -``` -constexpr int32_t OHOS::AVSession::AVSESSION_SUCCESS = 0 -``` -**描述:** -操作成功 - - -### ERR_ABILITY_NOT_AVAILABLE - - -``` -constexpr int32_t OHOS::AVSession::ERR_ABILITY_NOT_AVAILABLE = -(AVSESSION_ERROR_BASE + 16) -``` -**描述:** -元能力启动超失败 - - -### ERR_COMMAND_NOT_SUPPORT - - -``` -constexpr int32_t OHOS::AVSession::ERR_COMMAND_NOT_SUPPORT = -(AVSESSION_ERROR_BASE + 10) -``` -**描述:** -会话命令不支持 - - -### ERR_COMMAND_SEND_EXCEED_MAX - - -``` -constexpr int32_t OHOS::AVSession::ERR_COMMAND_SEND_EXCEED_MAX = -(AVSESSION_ERROR_BASE + 18) -``` -**描述:** -指令发送次数超过最大值 - - -### ERR_CONTROLLER_IS_EXIST - - -``` -constexpr int32_t OHOS::AVSession::ERR_CONTROLLER_IS_EXIST = -(AVSESSION_ERROR_BASE + 14) -``` -**描述:** -控制器存在 - - -### ERR_CONTROLLER_NOT_EXIST - - -``` -constexpr int32_t OHOS::AVSession::ERR_CONTROLLER_NOT_EXIST = -(AVSESSION_ERROR_BASE + 11) -``` -**描述:** -控制器不存在 - - -### ERR_INVALID_PARAM - - -``` -constexpr int32_t OHOS::AVSession::ERR_INVALID_PARAM = -(AVSESSION_ERROR_BASE + 2) -``` -**描述:** -传递的参数无效 - - -### ERR_IPC_SEND_REQUEST - - -``` -constexpr int32_t OHOS::AVSession::ERR_IPC_SEND_REQUEST = -(AVSESSION_ERROR_BASE + 7) -``` -**描述:** -IPC发送数据失败 - - -### ERR_MARSHALLING - - -``` -constexpr int32_t OHOS::AVSession::ERR_MARSHALLING = -(AVSESSION_ERROR_BASE + 5) -``` -**描述:** -数据序列化操作错误 - - -### ERR_NO_MEMORY - - -``` -constexpr int32_t OHOS::AVSession::ERR_NO_MEMORY = -(AVSESSION_ERROR_BASE + 1) -``` -**描述:** -无可用内存 - - -### ERR_NO_PERMISSION - - -``` -constexpr int32_t OHOS::AVSession::ERR_NO_PERMISSION = -(AVSESSION_ERROR_BASE + 12) -``` -**描述:** -无权限 - - -### ERR_RPC_SEND_REQUEST - - -``` -constexpr int32_t OHOS::AVSession::ERR_RPC_SEND_REQUEST = -(AVSESSION_ERROR_BASE + 19) -``` -**描述:** -RPC发送数据失败 - - -### ERR_SERVICE_NOT_EXIST - - -``` -constexpr int32_t OHOS::AVSession::ERR_SERVICE_NOT_EXIST = -(AVSESSION_ERROR_BASE + 3) -``` -**描述:** -服务不存在 - - -### ERR_SESSION_DEACTIVE - - -``` -constexpr int32_t OHOS::AVSession::ERR_SESSION_DEACTIVE = -(AVSESSION_ERROR_BASE + 13) -``` -**描述:** -会话未激活 - - -### ERR_SESSION_EXCEED_MAX - - -``` -constexpr int32_t OHOS::AVSession::ERR_SESSION_EXCEED_MAX = -(AVSESSION_ERROR_BASE + 8) -``` -**描述:** -超过允许会话最大数量 - - -### ERR_SESSION_LISTENER_EXIST - - -``` -constexpr int32_t OHOS::AVSession::ERR_SESSION_LISTENER_EXIST = -(AVSESSION_ERROR_BASE + 4) -``` -**描述:** -Session监听器已存在 - - -### ERR_SESSION_NOT_EXIST - - -``` -constexpr int32_t OHOS::AVSession::ERR_SESSION_NOT_EXIST = -(AVSESSION_ERROR_BASE + 9) -``` -**描述:** -会话不存在 - - -### ERR_START_ABILITY_IS_RUNNING - - -``` -constexpr int32_t OHOS::AVSession::ERR_START_ABILITY_IS_RUNNING = -(AVSESSION_ERROR_BASE + 15) -``` -**描述:** -元能力正在运行 - - -### ERR_START_ABILITY_TIMEOUT - - -``` -constexpr int32_t OHOS::AVSession::ERR_START_ABILITY_TIMEOUT = -(AVSESSION_ERROR_BASE + 17) -``` -**描述:** -元能力启动超时 - - -### ERR_UNMARSHALLING - - -``` -constexpr int32_t OHOS::AVSession::ERR_UNMARSHALLING = -(AVSESSION_ERROR_BASE + 6) -``` -**描述:** -数据反序列化操作错误 diff --git a/zh-cn/application-dev/reference/native-apis/avsession__info_8h.md b/zh-cn/application-dev/reference/native-apis/avsession__info_8h.md deleted file mode 100644 index 5d2eda467fc5949921b3942c5282c0073c4aafda..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avsession__info_8h.md +++ /dev/null @@ -1,75 +0,0 @@ -# avsession_info.h - - -## 概述 - -定义了与avsession相关的监听器以及回调功能的实现。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::SessionListener](_o_h_o_s_1_1_a_v_session_1_1_session_listener.md) | class
定义与AVSession相关监听器的类的实现。 | -| [OHOS::AVSession::AVSessionCallback](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_callback.md) | class
定义AVSession回调类的实现 | -| [OHOS::AVSession::AVControllerCallback](_h_o_s_1_1_a_v_session_1_1_a_v_controller_callback.md) | class
定义控制器相关回调操作的类的实现。 | -| [OHOS::AVSession::SessionToken](_o_h_o_s_1_1_a_v_session_1_1_session_token.md) | struct
会话令牌的信息。 | - - -### 类型定义 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::DeathCallback](#deathcallback) = std::function< void()> | using | - - -### 枚举 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::SessionDataCategory](#sessiondatacategory) {
**OHOS::AVSession::SESSION_DATA_CATEGORY_INVALID** = -1, **OHOS::AVSession::SESSION_DATA_META** = 0, **OHOS::AVSession::SESSION_DATA_PLAYBACK_STATE** = 1, **OHOS::AVSession::SESSION_DATA_CONTROL_COMMAND** = 2, **OHOS::AVSession::SESSION_DATA_CATEGORY_MAX** = 3
} | 会话元数据处理标识 | - - -## 类型定义说明 - - -### DeathCallback - - -``` -using OHOS::AVSession::DeathCallback = typedef std::function -``` -**描述:** -AVSession死亡回调 - - -## 枚举类型说明 - - -### SessionDataCategory - - -``` -enum OHOS::AVSession::SessionDataCategory -``` -**描述:** -会话元数据处理标识 - - | 枚举值 | 描述 | -| -------- | -------- | -| SESSION_DATA_CATEGORY_INVALID | 无效类型,内部用于类型是否有效 | -| SESSION_DATA_META | 会话元数据 | -| SESSION_DATA_PLAYBACK_STATE | 会话播放状态 | -| SESSION_DATA_CONTROL_COMMAND | 会话控制命令 | -| SESSION_DATA_CATEGORY_MAX | 会话数据类型的数量 | diff --git a/zh-cn/application-dev/reference/native-apis/avsession__manager_8h.md b/zh-cn/application-dev/reference/native-apis/avsession__manager_8h.md deleted file mode 100644 index 86b408d3bbe022b581e4cd76d4d4b263a9be4069..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avsession__manager_8h.md +++ /dev/null @@ -1,24 +0,0 @@ -# avsession_manager.h - - -## 概述 - -定义了会话管理器对外接口的功能的实现。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVSessionManager](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_manager.md) | class
实现会话管理器对外接口功能的类的实现。 | diff --git a/zh-cn/application-dev/reference/native-apis/avsession__pixel__map_8h.md b/zh-cn/application-dev/reference/native-apis/avsession__pixel__map_8h.md deleted file mode 100644 index 0843e8fad66b4c434773b76b23c364399b5068ae..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/avsession__pixel__map_8h.md +++ /dev/null @@ -1,44 +0,0 @@ -# avsession_pixel_map.h - - -## 概述 - -读取、设置图片及图片信息。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 结构体 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::AVSessionPixelMap](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_pixel_map.md) | class
读取、设置图片及图片信息。 | - - -### 变量 - - | 名称 | 描述 | -| -------- | -------- | -| [OHOS::AVSession::DEFAULT_BUFFER_SIZE](#default_buffer_size) = 160 \* 1024 | constexpr size_t
初始化容器大小为160KB | - - -## 变量说明 - - -### DEFAULT_BUFFER_SIZE - - -``` -constexpr size_t OHOS::AVSession::DEFAULT_BUFFER_SIZE = 160 * 1024 -``` -**描述:** -初始化容器大小为160KB diff --git a/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_basic_info.md b/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_basic_info.md deleted file mode 100644 index 7f80f23b753371a6b308fb2d8d8dce089db69ab3..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_basic_info.md +++ /dev/null @@ -1,37 +0,0 @@ -# OHOS::AVSession::AVSessionBasicInfo - - -## 概述 - -会话基础信息描述。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### 成员变量 - - | 名称 | 描述 | -| -------- | -------- | -| [deviceName_](avsession.md#devicename) {} | std::string | -| [networkId_](avsession.md#networkid) {} | std::string | -| [vendorId_](avsession.md#vendorid) {} | std::string | -| [deviceType_](avsession.md#devicetype) {} | std::string | -| [systemVersion_](avsession.md#systemversion) {} | std::string | -| [sessionVersion_](avsession.md#sessionversion) {} | int32_t | -| [reserve_](avsession.md#reserve) {} | std::vector< int32_t > | -| [feature_](avsession.md#feature) {} | std::vector< int32_t > | -| [metaDataCap_](avsession.md#metadatacap) {} | std::vector< int32_t > | -| [playBackStateCap_](avsession.md#playbackstatecap) {} | std::vector< int32_t > | -| [controlCommandCap_](avsession.md#controlcommandcap) {} | std::vector< int32_t > | -| [extendCapability_](avsession.md#extendcapability) {} | std::vector< int32_t > | -| [systemTime_](avsession.md#systemtime) {} | int32_t | -| [extend_](avsession.md#extend) {} | std::vector< int32_t > | diff --git a/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md b/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md deleted file mode 100644 index 337f6045d9771b88cc7e253a8a5ae616ca95aa3b..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_controller.md +++ /dev/null @@ -1,328 +0,0 @@ -# OHOS::AVSession::AVSessionController - - -## 概述 - -控制器对象,可获取会话的播放状态和会话元数据,远程发送控制命令到会话端也可以通过订阅监听会话段的更新事件。 - - -## 汇总 - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [GetAVPlaybackState](#getavplaybackstate) ([AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md) &state)=0 | 获取音视频的播放状态。  | -| [GetAVMetaData](#getavmetadata) ([AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md) &data)=0 | 获取会话元数据。  | -| [SendAVKeyEvent](#sendavkeyevent) (const MMI::KeyEvent &keyEvent)=0 | 发送系统按键事件。  | -| [GetLaunchAbility](#getlaunchability) (AbilityRuntime::WantAgent::WantAgent &ability)=0 | 获取Ability。  | -| [GetValidCommands](#getvalidcommands) (std::vector< int32_t > &cmds)=0 | 获取媒体有效的指令。  | -| [IsSessionActive](#issessionactive) (bool &isActive)=0 | 获取session的激活状态。  | -| [SendControlCommand](#sendcontrolcommand) (const [AVControlCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md) &cmd)=0 | 发送媒体控制指令。  | -| [RegisterCallback](#registercallback) (const std::shared_ptr< [AVControllerCallback](_h_o_s_1_1_a_v_session_1_1_a_v_controller_callback.md) > &callback)=0 | 注册回调。  | -| [SetMetaFilter](#setmetafilter) (const [AVMetaData::MetaMaskType](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md#metamasktype) &filter)=0 | 设置会话元数据过滤。  | -| [SetPlaybackFilter](#setplaybackfilter) (const AVPlaybackState::PlaybackStateMaskType &filter)=0 | 设置音视频的播放状态回调过滤。  | -| [Destroy](#destroy) ()=0 | 释放控制器。  | -| [GetSessionId](#getsessionid) ()=0 | 获取sessionId。  | -| [GetRealPlaybackPosition](#getrealplaybackposition) ()=0 | 获取播放的实时位置,第 x ms。  | -| [IsDestroy](#isdestroy) ()=0 | 是否释放控制器。  | - - -## 成员函数说明 - - -### Destroy() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::Destroy () -``` -**描述:** -释放控制器。 - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### GetAVMetaData() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::GetAVMetaData (AVMetaData & data) -``` -**描述:** -获取会话元数据。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| data | 会话元数据[AVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md)。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[AVSession::SetAVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#setavmetadata) - -[AVSession::GetAVMetaData](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#getavmetadata) - - -### GetAVPlaybackState() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::GetAVPlaybackState (AVPlaybackState & state) -``` -**描述:** -获取音视频的播放状态。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| state | 音视频的播放状态[AVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_playback_state.md)。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[AVSession::SetAVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#setavplaybackstate) - -[AVSession::GetAVPlaybackState](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#getavplaybackstate) - - -### GetLaunchAbility() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::GetLaunchAbility (AbilityRuntime::WantAgent::WantAgent & ability) -``` -**描述:** -获取Ability。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| ability | 类型为**AbilityRuntime::WantAgent::WantAgent**。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[AVSession::SetLaunchAbility](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#setlaunchability) - - -### GetRealPlaybackPosition() - - -``` -virtual int64_t OHOS::AVSession::AVSessionController::GetRealPlaybackPosition () -``` -**描述:** -获取播放的实时位置,第 x ms。 - -**返回:** - -返回播放的实时位置,第x ms,经过校正过的时间,单位为ms。 - - -### GetSessionId() - - -``` -virtual std::string OHOS::AVSession::AVSessionController::GetSessionId () -``` -**描述:** -获取sessionId。 - -**返回:** - -返回sessionId。 - - -### GetValidCommands() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::GetValidCommands (std::vector< int32_t > & cmds) -``` -**描述:** -获取媒体有效的指令。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| cmds | 媒体有效的指令列表,范围为**SESSION_CMD_INVALID**到**SESSION_CMD_MAX**。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[SendControlCommand](#sendcontrolcommand) - -[AVSession::AddSupportCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#addsupportcommand) - -[AVSession::DeleteSupportCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#deletesupportcommand) - - -### IsDestroy() - - -``` -virtual bool OHOS::AVSession::AVSessionController::IsDestroy () -``` -**描述:** -是否释放控制器。 - -**返回:** - -true:释放;false:不释放。 - - -### IsSessionActive() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::IsSessionActive (bool & isActive) -``` -**描述:** -获取session的激活状态。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| isActive | session是否激活。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[AVSession::Activate](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#activate) - -[AVSession::Deactivate](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#deactivate) - -[AVSession::IsActive](_o_h_o_s_1_1_a_v_session_1_1_a_v_session.md#isactive) - - -### RegisterCallback() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::RegisterCallback (const std::shared_ptr< AVControllerCallback > & callback) -``` -**描述:** -注册回调。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| callback | 需要注册的回调,类型为[AVControllerCallback](_h_o_s_1_1_a_v_session_1_1_a_v_controller_callback.md)。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### SendAVKeyEvent() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::SendAVKeyEvent (const MMI::KeyEvent & keyEvent) -``` -**描述:** -发送系统按键事件。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| keyEvent | 按键事件码,类型为**MMI::KeyEvent**。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[AVSessionManager::SendSystemAVKeyEvent](_o_h_o_s_1_1_a_v_session_1_1_a_v_session_manager.md#sendsystemavkeyevent) - - -### SendControlCommand() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::SendControlCommand (const AVControlCommand & cmd) -``` -**描述:** -发送媒体控制指令。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| cmd | 媒体控制指令,类型为[AVControlCommand](_o_h_o_s_1_1_a_v_session_1_1_a_v_control_command.md)。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - -**参见:** - -[GetValidCommands](#getvalidcommands) - - -### SetMetaFilter() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::SetMetaFilter (const AVMetaData::MetaMaskType & filter) -``` -**描述:** -设置会话元数据过滤。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| filter | 会话元数据过滤,类型为[AVMetaData#MetaMaskType](_o_h_o_s_1_1_a_v_session_1_1_a_v_meta_data.md#metamasktype)。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 - - -### SetPlaybackFilter() - - -``` -virtual int32_t OHOS::AVSession::AVSessionController::SetPlaybackFilter (const AVPlaybackState::PlaybackStateMaskType & filter) -``` -**描述:** -设置音视频的播放状态回调过滤。 - -**参数:** - - | 名称 | 描述 | -| -------- | -------- | -| filter | 音视频播放状态回调过滤,类型为**AVPlaybackState\#PlaybackStateMaskType**。  | - -**返回:** - -成功返回**AVSESSION_SUCCESS**;失败则返回对应错误码。 diff --git a/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md b/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md deleted file mode 100644 index c68f7cf38878d2290dd1180136535069110604a3..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/o_h_o_s_1_1_a_v_session_1_1_a_v_session_descriptor.md +++ /dev/null @@ -1,41 +0,0 @@ -# OHOS::AVSession::AVSessionDescriptor - - -## 概述 - -会话的相关描述信息。 - -**起始版本:** -9 -**Version:** -1.0 -**相关模块:** - -[Avsession](avsession.md) - - -## 汇总 - - -### Public 成员函数 - - | 名称 | 描述 | -| -------- | -------- | -| [WriteToParcel](avsession.md#writetoparcel) (Parcel &out) const | 将会话相关描述信息写进包里。  | -| [ReadFromParcel](avsession.md#readfromparcel) (Parcel &in) | 对会话相关描述信息进行解包。  | - - -### 成员变量 - - | 名称 | 描述 | -| -------- | -------- | -| [sessionId_](avsession.md#sessionid) | std::string | -| [sessionType_](avsession.md#sessiontype) {} | int32_t | -| [sessionTag_](avsession.md#sessiontag) | std::string | -| [elementName_](avsession.md#elementname) | AppExecFwk::ElementName | -| [pid_](avsession.md#pid) {} | pid_t | -| [uid_](avsession.md#uid) {} | pid_t | -| [isActive_](avsession.md#isactive) {} | bool | -| [isTopSession_](avsession.md#istopsession) {} | bool | -| [isThirdPartyApp_](avsession.md#isthirdpartyapp) {} | bool | -| [outputDeviceInfo_](avsession.md#outputdeviceinfo) | [OutputDeviceInfo](_o_h_o_s_1_1_a_v_session_1_1_output_device_info.md) | diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index 1283ebfadca8af998e9b7dbe7fe521feb557896e..189cba7a454da7e6802571b3172fe78e0d319398 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -924,6 +924,16 @@ **ACL使能**:TRUE +## ohos.permission.ENTERPRISE_RESET_DEVICE + +允许设备管理员恢复设备出厂设置。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + ## ohos.permission.NFC_TAG 允许应用读取Tag卡片。 @@ -1602,4 +1612,14 @@ **授权方式**:system_grant -**ACL使能**:TRUE \ No newline at end of file +**ACL使能**:TRUE + +## ohos.permission.ACCESS_SCREEN_LOCK_INNER + +允许应用调用锁屏服务的系统API。 + +**权限级别**:system_core + +**授权方式**:system_grant + +**ACL使能**:FALSE \ No newline at end of file diff --git a/zh-cn/application-dev/tools/aa-tool.md b/zh-cn/application-dev/tools/aa-tool.md index fef305b1cdfde1530a69630e8967c73dc7064fd4..3a5665c2767600fbb10d83fe4bc97ce5ba5fe5d5 100644 --- a/zh-cn/application-dev/tools/aa-tool.md +++ b/zh-cn/application-dev/tools/aa-tool.md @@ -68,7 +68,7 @@ Ability assistant(Ability助手,简称为aa),是实现应用及测试用 | -------- | -------- | -------- | | -h/--help | - | 帮助信息。 | | -a/--all | - | 打印所有mission内的应用组件信息。 | - | -l/--mission-list | type(缺省打印全部) | 打印任务栈信息。
可取值:
- NORMAL
- DEFAULT_STANDARD
- DEFAULT_SINGLE
- LAUNCHER | + | -l/--mission-list | type(缺省打印全部) | 服务侧为了方便管理任务链,内部维护了4种类型的任务链。
可取值:
- NORMAL: 正常启动的任务链(比如A拉起B拉起C, 则对应的任务链是A->B->C)
- DEFAULT_STANDARD: 已经被破坏的任务链中的任务, 启动模式为standard的任务被放到该任务链中, 这里面的任务之间没有关联关系
- DEFAULT_SINGLE: 已经被破坏的任务链中的任务, 启动模式为singleton的任务被放到该任务链中, 这里面的任务之间没有关联关系
- LAUNCHER: launcher的任务链 | | -e/--extension | elementName | 打印扩展组件信息。 | | -u/--userId | UserId | 打印指定UserId的栈信息,需要和其他参数组合使用,例如aa dump -a -u 100、aa dump -d -u 100。 | | -d/--data | - | 打印DataAbility相关信息。 | diff --git a/zh-cn/device-dev/driver/driver-platform-gpio-des.md b/zh-cn/device-dev/driver/driver-platform-gpio-des.md index b2d1db7482526a64656b2608848d2f599a10bcc0..a0f63441d9305fb97fd829f6792ffe71a7923d24 100644 --- a/zh-cn/device-dev/driver/driver-platform-gpio-des.md +++ b/zh-cn/device-dev/driver/driver-platform-gpio-des.md @@ -146,17 +146,17 @@ if (ret != 0) { int32_t GpioGetDir(uint16_t gpio, uint16_t *dir); ``` -**表2** GpioGetDir参数和返回值描述 +**表3** GpioGetDir参数和返回值描述 | **参数** | **参数描述** | | ---------- | ------------------ | | gpio | GPIO管脚号 | -| dir | 待获取的方向值 | +| dir | 获取到的方向值指针 | | **返回值** | **返回值描述** | | 0 | 设置成功 | | 负数 | 设置失败 | -假设需要将GPIO管脚3的方向配置为输出,其使用示例如下: +假设需要获取GPIO管脚3的方向,其使用示例如下: ```c int32_t ret; @@ -177,7 +177,7 @@ if (ret != 0) { int32_t GpioRead(uint16_t gpio, uint16_t *val); ``` -**表3** GpioRead参数和返回值描述 +**表4** GpioRead参数和返回值描述 | **参数** | **参数描述** | | ---------- | -------------------- | @@ -208,7 +208,7 @@ if (ret != 0) { int32_t GpioWrite(uint16_t gpio, uint16_t val); ``` -**表4** GpioWrite参数和返回值描述 +**表5** GpioWrite参数和返回值描述 | **参数** | **参数描述** | | ---------- | ------------------ | @@ -238,7 +238,7 @@ if (ret != 0) { int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); ``` -**表5** GpioSetIrq参数和返回值描述 +**表6** GpioSetIrq参数和返回值描述 | **参数** | **参数描述** | | ---------- | ------------------------ | @@ -261,7 +261,7 @@ int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); int32_t GpioUnsetIrq(uint16_t gpio, void *arg); ``` -**表6** GpioUnsetIrq参数和返回值描述 +**表7** GpioUnsetIrq参数和返回值描述 | **参数** | **参数描述** | | ---------- | -------------- | @@ -279,7 +279,7 @@ int32_t GpioUnsetIrq(uint16_t gpio, void *arg); int32_t GpioEnableIrq(uint16_t gpio); ``` -**表7** GpioEnableIrq参数和返回值描述 +**表8** GpioEnableIrq参数和返回值描述 | **参数** | **参数描述** | | ---------- | -------------- | @@ -298,7 +298,7 @@ int32_t GpioEnableIrq(uint16_t gpio); ```c int32_t GpioDisableIrq(uint16_t gpio); ``` -**表8** GpioDisableIrq参数和返回值描述 +**表9** GpioDisableIrq参数和返回值描述 | **参数** | **参数描述** | | ---------- | -------------- | diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001275586896.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001275586896.png deleted file mode 100644 index cee1d83517ee1fced5373f51cefb12e91346e947..0000000000000000000000000000000000000000 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001275586896.png and /dev/null differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001285806330.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001285806330.png deleted file mode 100644 index 5e8e45b85dbbda22db008150b798f0c984394642..0000000000000000000000000000000000000000 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001285806330.png and /dev/null differ diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md new file mode 100644 index 0000000000000000000000000000000000000000..9bafd21ac6fb7ae6c2c408565476ece681a45c4d --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md @@ -0,0 +1,150 @@ +# OpenHarmony 3.1.5 Release + + +## 版本概述 + +当前版本在OpenHarmony 3.1.4 Release的基础上,修复了内存泄漏及linux kernel等开源组件的安全漏洞,增强了系统安全性。修复了部分系统稳定性的issue,增强了系统稳定性。更新配套的SDK版本,修复了预览器相关的问题。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.1.5 Release | NA | +| Full SDK | Ohos_sdk_full 3.1.11.5 (API Version 8 Relese) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md)。 | +| Public SDK | Ohos_sdk_public 3.1.11.5 (API Version 8 Release) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
DevEco Studio 3.0 Beta4版本起,通过DevEco Studio获取的SDK默认为Public SDK。 | +| HUAWEI DevEco Studio(可选) | 3.1 Preview for OpenHarmony | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 3.0 Release | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee账号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)** + +通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.5-Release --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.1.5-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + +**表2** 获取源码路径 + +| 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/OpenHarmony-v3.1.5-Release.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/OpenHarmony-v3.1.5-Release.tar.gz.sha256) | +| Hi3516标准系统解决方案(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_hi3516.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_hi3516.tar.gz.sha256) | +| RK3568标准系统解决方案(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_rk3568.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_rk3568.tar.gz.sha256) | +| Hi3861轻量系统解决方案(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_pegasus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_pegasus.tar.gz.sha256) | +| Hi3516小型系统解决方案-LiteOS(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus.tar.gz.sha256) | +| Hi3516小型系统解决方案-Linux(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus_linux.tar.gz.sha256) | +| 标准系统Full SDK包(Mac) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-full.tar.gz.sha256) | +| 标准系统Full SDK包(Windows\Linux) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-full.tar.gz.sha256) | +| 标准系统Public SDK包(Mac) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-public.tar.gz.sha256) | +| 标准系统Public SDK包(Windows\Linux) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-public.tar.gz.sha256) | + + +## 更新说明 + +本版本在OpenHarmony 3.1.4 Release的基础上有如下变更。 + + +### 特性变更 + +本次版本无新增特性及变更。 + +### API变更 + +3.1.5 Release对比3.1.4 Release API接口无变更。 + + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +### 修复缺陷列表 + +**表3** 修复缺陷issue列表 + +| 子系统 | 问题描述 | +| -------------- | ------------------------------------------------------------ | +| SDK子系统 | 修复了预览器相关的一些问题。 | +| 网络管理子系统 | 进程com.ohos.netmanagersocket下线程1.ui出现了异常栈libconnection.z.so([I5IXWZ](https://gitee.com/openharmony/communication_netmanager_base/issues/I5IXWZ)) | +| Misc子系统 | request.download 下载时概率不上报complete事件([I5WZC6](https://gitee.com/openharmony/request_request/issues/I5WZC6)) | +| DFX子系统 | hdcd低概率出现cpp_crash([I65P94](https://gitee.com/openharmony/developtools_hdc/issues/I65P94)) | +| Arkui子系统 | 修复获焦组件通用属性异常的问题([I64YLA](https://gitee.com/openharmony/arkui_ace_engine/issues/I64YLA)) | + + + + +### 修复安全漏洞列表 + +**表4** 修复安全问题列表 + +| ISSUE | 问题描述 | 修复链接 | +| -------- | -------- | -------- | +| I5UHSG | 修复组件das u-boot上的CVE-2022-2347安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_u-boot/pulls/62) | +| I5UI3F/I5VGDV | 修复组件kernel_linux_5.10上的CVE-2022-3303、CVE-2022-42703、CVE-2022-20422、CVE-2022-41222、CVE-2022-3239、CVE-2022-20423、CVE-2022-41850安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_expat/pulls/23) | +| I5XU3W | 修复组件kernel_linux_5.10上的CVE-2022-3586、CVE-2022-3625、CVE-2022-42432、CVE-2022-3633、CVE-2022-3635、CVE-2022-3629、CVE-2022-3623、CVE-2022-3646、CVE-2022-3621、CVE-2022-3567、CVE-2022-43750、CVE-2022-3545、CVE-2022-2978、CVE-2022-3523、CVE-2022-2602、CVE-2022-3628安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/541) | +| I5XUCJ | 修复组件kernel_linux_5.10上的CVE-2022-40768、CVE-2022-3577、CVE-2022-20409、CVE-2022-3566、CVE-2022-3606、CVE-2022-3564、CVE-2022-3649安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/505) | +| I5VGIU | 修复组件kernel_linux_5.10上的CVE-2022-3169安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/553) | +| I63VFW | 修复组件kernel_linux_5.10上的CVE-2022-41858安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/569) | +| I63VG7 | 修复组件kernel_linux_5.10上的CVE-2022-45934、CVE-2022-4129、CVE-2022-4378、CVE-2022-3108、CVE-2022-47518、CVE-2022-47521、CVE-2022-47519、CVE-2022-47520安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/586) | +| I66ZCI | 修复组件kernel_linux_5.10上的CVE-2022-3105、CVE-2022-3104、CVE-2022-3115、CVE-2022-3113、CVE-2022-3112安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/579) | +| I66ZHX | 修复组件kernel_linux_5.10上的CVE-2022-3111安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/584) | +| I66ZKM | 修复组件kernel_linux_5.10上的CVE-2022-3107安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/590) | +| I65T2H | 修复组件kernel_linux_5.10上的CVE-2022-20566安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/582) | +| I61HGX | 修复组件kernel_linux_5.10上的CVE-2022-42895、CVE-2022-42896安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/545) | +| I652LY | 修复组件kernel_linux_5.10上的CVE-2022-4139安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/567) | +| I65R2K | 修复组件python上的CVE-2022-42919安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/36) | +| I65R59 | 修复组件python上的CVE-2022-45061安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/37) | +| I65UJ8 | 修复组件python上的CVE-2022-45061安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/35) | +| I60GOT | 修复组件pixman上的CVE-2022-37454安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_pixman/pulls/11) | +| I5Z39U | 修复组件curl上的CVE-2022-32221、CVE-2022-42915、CVE-2022-42916安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_curl/pulls/91) | +| I61I8F | 修复组件ntfs-3g上的CVE-2022-40284安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_ntfs-3g/pulls/33) | +| I63V9Z | 修复组件libxml2上的CVE-2022-40303、CVE-2022-40304安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_libxml2/pulls/31) | diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md index 23f4ce5addb9e28937c2ca0033159fd160515eaf..44cfb4d87f548d6f399b822afd2b586d34584577 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md @@ -2,8 +2,8 @@ OpenHarmony 3.2.10.1(Mr)版本相较于OpenHarmony 3.2.beta4版本,container子系统的API变更如下 -## cl.commonlibrary.1 错误码及信息变更 -commonlibrary子系统中ArrayList、List、LinkedList、Stack、Queue、Deque、PlainArray、LightWeightMap、LightWeightSet、HashMap、HashSet、TreeMap、TreeSet类的接口抛出的错误码及信息变更: +## cl.公共基础类库子系统.1 错误码及信息变更 +公共基础类库子系统子系统中ArrayList、List、LinkedList、Stack、Queue、Deque、PlainArray、LightWeightMap、LightWeightSet、HashMap、HashSet、TreeMap、TreeSet类的接口抛出的错误码及信息变更: 变更后的错误码详细介绍请参见[语言基础类库错误码](../../../application-dev/reference/errorcodes/errorcode-utils.md)。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md index 6fda579d33b819b57f49cb25db9a1e49b37030fb..c9ea0328d415ce1504c57eeabe79e3bb3dabcbc9 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md @@ -1,9 +1,9 @@ -# url系统JS API变更Changelog +# 公共基础类库子系统JS API变更Changelog OpenHarmony 3.2.10.1(Mr)版本相较于OpenHarmony 3.2.beta4版本,url子系统的API变更如下 -## cl.url.1.URLParams类接口变更 -url子系统URLParams类构造函数存在变更: +## cl.commonlibrary.1.URLParams类接口变更 +公共基础类库子系统url模块URLParams类构造函数存在变更: constructor(init?: string[][] | Record | string | URLSearchParams) 改为 constructor(init?: string[][] | Record | string | URLParams);参数类型为原来的URLSearchParams类改为URLParams类。 @@ -37,8 +37,8 @@ try { console.error(`Fail to ceate URLParams.codeis${err.code},message is ${err.message}`); } ``` -## cl.url.2.URL类属性变更url子系统URLParams类构造函数存在变更: -url子系统URL类属性存在变更: +## cl.commonlibrary.2.URL类属性变更url子系统URLParams类构造函数存在变更: +公共基础类库子系统url模块URL类属性存在变更: 废弃searchParams: URLSearchParams属性,新增params: URLParams属性 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md new file mode 100644 index 0000000000000000000000000000000000000000..4ef6169a1e412d95b7ea091c17459ebd2bcc7b44 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md @@ -0,0 +1,36 @@ +# 帐号子系统changeLog + +## cl.account_os_account.1 createOsAccountForDomain错误码变更 + +使用createOsAccountForDomain重复创建域帐号时,变更前返回的错误码为12300001,变更后返回的错误码为12300004。 +错误信息由通用系统报错细化为帐号已存在报错。 + +**变更影响** + +基于此前版本开发的应用,需适配变更后的错误码,否则会影响原有业务逻辑。 + +**关键接口/组件变更** +- AccountManager + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>); + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo>; + +**适配指导** + +重复创建域帐号的示例代码如下: + +```ts +import account_osAccount from "@ohos.account.osAccount" +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' + +let accountMgr = account_osAccount.getAccountManager(); +let domainInfo = { + accountName: "zhangsan", + domain: "china.example.com" +}; +try { + await accountMgr.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo); + await accountMgr.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo); +} catch (err) { + expect(err.code).assertEqual(12300004); +} +``` diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-bundlemanager.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..7ca77c26ed3c3d1bcf03d5153c6b02b5ab53388e --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-bundlemanager.md @@ -0,0 +1,94 @@ +# 包管理子系统ChangeLog + +## cl.bundlemanager.1 底层能力变更,安装应用时增加签名证书中bundle-name的校验,需要与应用的bundleName相同,否则会安装失败。 + +安装应用时增加了对[签名证书profile文件](../../../application-dev/security/app-provision-structure.md)中bundle-name字段的校验,该字段内容需要配置为对应应用的bundleName。 + +如果bundle-name的内容与应用配置文件中的bundleName不一致,会出现安装失败。具体报错为: +``` +error: verify signature failed. +``` + +**变更影响**
+对之前的版本镜像无影响,对使用3.2.10.5版本及之后的系统镜像,如果未修改签名证书中的bundle-name字段,会出现应用安装失败问题。 + +**关键的接口/组件变更**
+不涉及接口及组件变更 + +**适配指导**
+原有应用在新的系统镜像上出现'error: verify signature failed',可以修改签名证书profile文件中的bundle-name为对应应用的bundleName,生成新的签名证书(后缀为.p7b),重新给应用签名即可。 +签名工具及签名证书的生成方式可以参考:[签名工具指导](../../../application-dev/security/hapsigntool-guidelines.md) + +## cl.bundlemanager.2 底层能力变更,增加对无图标应用的管控,如果应用未配置入口图标,则会在桌面上显示一个默认图标,点击后跳转至应用详情页。 + +增加对无图标应用的管控,如果应用未配置入口图标且未申请隐藏图标特权(AllowHideDesktopIcon),则会在桌面上显示一个默认图标,点击后跳转至应用详情页。此处的未配置入口图标规则如下: +1. 应用中未配置abilities字段 +2. 应用中配置了abilities字段,但是没有任何一个page类型的ability中skills如下,即同时包含"action.system.home"和"entity.system.home": + ```json + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + ``` +对于符合上面规则的应用,均属于无图标应用,通过hdc_std install 或者 bm install的方式安装,均会在桌面上显示一个默认图标。 + +如果应用不需要再桌面显示图标,需要申请相应的隐藏图标特权AllowHideDesktopIcon,并在签名证书文件中或者白名单(install_list_capability.json)配置,可以参考:[应用特权配置指南](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md)。 + +如果应该需要在桌面显示图标,则需要在abilities中选择一个ability配置skills,同时包含"action.system.home"和"entity.system.home"。 + +**变更影响**
+对之前的版本镜像无影响,对使用3.2.10.5版本及之后的系统镜像,如果应用未配置图标,通过命令行的安装方式会在桌面显示默认图标。 + +**关键的接口/组件变更**
+不涉及接口及组件变更 + +**适配指导**
+如果应用不需要再桌面显示图标,需要申请相应的隐藏图标特权AllowHideDesktopIcon,并在签名证书文件中或者白名单(install_list_capability.json)配置,可以参考:[应用特权配置指南](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md)。 + +如果应该需要在桌面显示图标,则需要在abilities中选择一个ability配置skills,同时包含"action.system.home"和"entity.system.home"。 + +## cl.bundlemanager.3 底层能力变更,特权AllowAppUsePrivilegeExtension、AllowAppMultiProcess和AllowFormVisibleNotify不支持通过签名证书配置,仅支持通过白名单install_list_capability.json申请这三个特权。 + +特权AllowAppUsePrivilegeExtension、AllowAppMultiProcess和AllowFormVisibleNotify不支持通过签名证书配置,仅支持通过白名单install_list_capability.json申请这三个特权。对于在签名证书中申请使用上面三个特权的应用,在新版本上可能出现安装失败或者配置特权无效的问题。 + +如果出现了下面的报错,可能是因为特权整改导致的,应用需要适配新的规则,可以参考:[应用特权配置指南](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md)。 +``` +error: install parse profile prop check error. +``` + +对于xts或者本地调试的demo,无法修改板子上install_list_capability.json的,可以修改应用的bundleName,需要以"com.acts."为开头,同时在签名证书中申请对应的特权。 + +申请特权AllowAppUsePrivilegeExtension,通常是在应用的配置文件中使用了extensionAbilities字段,且其中的type属性为dataShare或者service。如果未配置特权,就会出现安装失败问题。 + +**变更影响**
+对之前的版本镜像无影响,对使用3.2.10.5版本及之后的系统镜像,如果未在白名单install_list_capability.json中申请所需的特权,可能会出现应用安装失败问题。 + +**关键的接口/组件变更**
+不涉及接口及组件变更 + +**适配指导**
+如果出现了下面的报错,可能是因为特权整改导致的,应用需要适配新的规则,可以参考:[应用特权配置指南](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md)。 +``` +error: install parse profile prop check error. +``` + +对于xts或者本地调试的demo,无法修改开发板上install_list_capability.json的,可以修改应用的bundleName,需要以"com.acts."为开头,同时在签名证书中申请对应的特权。 + +## cl.bundlemanager.4 底层能力变更,安装hap时,hap中的文件不再解压到安装目录。 + +安装hap后,安装目录下只会存在hap文件,应用不能再使用拼接路径访问解压后的资源文件,应用想要访问资源文件,需要使用标准的资源管理接口。 + +**变更影响**
+如果应用使用拼接路径的形式访问资源文件,会访问失败。需要修改成使用资源管理接口访问资源文件。 + +**关键的接口/组件变更**
+不涉及接口及组件变更 + +**适配指导**
+资源管理子系统提供Js接口访问资源文件。参考[访问资源文件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md#getrawfilecontent9) diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-useriam.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-useriam.md new file mode 100644 index 0000000000000000000000000000000000000000..0444bab5234087b1f865eda378e680c95fc1abb4 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-useriam.md @@ -0,0 +1,17 @@ +# 用户IAM子系统Changelog + +## cl.useriam.1 API9返回值命名变更 + +用户IAM API9的返回值枚举类类名发生变更,从 ResultCodeV9 更名为 UserAuthResultCode + +**变更影响** + +基于此版本以前开发的应用不受影响,以后的需适配错误码的类名,否则会影响业务逻辑。 + +**关键接口/组件变更** + +无接口/组件变更 + +**适配指导** + +需要修改返回值调用类名从 ResultCodeV9 改为 UserAuthResultCode \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md b/zh-cn/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md new file mode 100644 index 0000000000000000000000000000000000000000..b8baef9aa857112649ac8dec9b388be3624f4bd8 --- /dev/null +++ b/zh-cn/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md @@ -0,0 +1,57 @@ +# 帐号子系统changeLog + +## cl.account_os_account.1 系统帐号OsAccountInfo.type取值类型变更 + +变更前,OsAccountInfo.type取值的实际类型为Object,与d.ts中声明的OsAccountType枚举类型不一致;变更后,OsAccountInfo.type取值的实际类型为OsAccountType枚举。 + +**变更影响** + +基于此前版本开发的应用,需变更OsAccountInfo.type值的读取方式,否则影响原因业务逻辑。 + +**关键接口/组件变更** + +涉及的接口: +- AccountManager + - queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>>): void; + - queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>>; + - createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback<OsAccountInfo>): void; + - createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInfo>; + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>): void; + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo>; + - queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void; + - queryCurrentOsAccount(): Promise<OsAccountInfo>; + - getCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void; + - getCurrentOsAccount(): Promise<OsAccountInfo>; + - queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo>): void; + - queryOsAccountById(localId: number): Promise<OsAccountInfo>; + + - getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void; + - getOsAccountTypeFromProcess(): Promise<OsAccountType>; + - getOsAccountType(callback: AsyncCallback<OsAccountType>): void; + - getOsAccountType(): Promise<OsAccountType>; + +**适配指导** +```ts +import account_osAccount from "@ohos.account.osAccount" +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' + +let accountMgr = account_osAccount.getAccountManager(); +accountMgr.createOsAccount('account_test', account_osAccount.OsAccountType.GUEST).then((accountInfo) => { + expect(accountInfo.type).assertEqual(account_osAccount.OsAccountType.GUEST); + accountMgr.activateOsAccount(accountInfo.localId).then(() => { + console.log('activateOsAccount successfully'); + accountMgr.getOsAccountTypeFromProcess().then((accountType) => { + expect(accountType).assertEqual(account_osAccount.OsAccountType.GUEST); + }).catch((err) => { + console.log('activateOsAccount err: ' + JSON.stringify(err)); + expect().assertFail(); + }); + }).catch((err) => { + console.log('activateOsAccount err: ' + JSON.stringify(err)); + expect().assertFail(); + }); +}).catch((err) => { + console.log('createOsAccount err: ' + JSON.stringify(err)); + expect().assertFail(); +}); +```