diff --git a/CODEOWNERS b/CODEOWNERS index 9d7e915103f7fa3ba7dc3d9cc9845fec3fe6761c..ca2ba48baa68fb4990cc3e34fcf9ee5537ef1c28 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -198,6 +198,9 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-display.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen @@ -316,6 +319,8 @@ zh-cn/application-dev/reference/apis/js-apis-testRunner.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-uitest.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease zh-cn/application-dev/quick-start/start-overview.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang diff --git a/OAT.xml b/OAT.xml index 23f7ee1c6a4bbd0a0fc4e65dd810fc904ced5005..8cc884632d4a963fa921c5905cfbf96e7e22edb7 100644 --- a/OAT.xml +++ b/OAT.xml @@ -38,13 +38,13 @@ - + - + diff --git a/README_zh.md b/README_zh.md index c50955d1202d5ba0e2f6461841f9c551f2fc7c58..3c65434aac3acaee899db2e1eba85e61c03de5a5 100644 --- a/README_zh.md +++ b/README_zh.md @@ -26,7 +26,7 @@ - OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。 - 该版本已更新至OpenHarmony 3.0.3 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.3-LTS.md)了解版本详情。 + 该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。 - OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。 diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability/ability-brief.md index 283037aedc8c219bee48511898dd300a0c05dc3b..187064a1c67d7bd21c823a945cca79366428d3f8 100644 --- a/en/application-dev/ability/ability-brief.md +++ b/en/application-dev/ability/ability-brief.md @@ -29,6 +29,3 @@ In addition, the following differences exist in the development process: For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). -## Samples -The following sample is provided to help you better understand how to develop abilities: -- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility) diff --git a/en/application-dev/ability/fa-brief.md b/en/application-dev/ability/fa-brief.md index e3374b85a5e16e76a4b13dc58b1950e442a1313b..b89c15504376f326629dd2b3dd537e1633d986d0 100644 --- a/en/application-dev/ability/fa-brief.md +++ b/en/application-dev/ability/fa-brief.md @@ -26,17 +26,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other. ![fa-threading-model](figures/fa-threading-model.png) -## Samples -The following sample is provided to help you better understand how to develop abilities: - -- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc) -- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti) - -- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA) -- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo) -- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) -- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH) -- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) -- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) -- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) -- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) diff --git a/en/application-dev/ability/fa-dataability.md b/en/application-dev/ability/fa-dataability.md index f7bcf858e15b2f7f16b0327b1b91097e2f28facd..d291124c123f0f8e30ef344179a8891c67972b81 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability/fa-dataability.md @@ -1,9 +1,34 @@ # Data Ability Development + ## When to Use + A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices. Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs. +## URI Introduction + +A Uniform Resource Identifier (URI) is used to identify a specific data item, such as a table in the database or a file on the disk. URIs used in OpenHarmony comply with the commonly used URI standard. A URI consists of the components: + +![fa-dataability-uri](figures/fa-dataability-uri.png) + +- **scheme**: name of the scheme used by the Data ability. The value is fixed at **dataability**. +- **authority**: device ID. To access data on a remote device, set this component to the ID of the remote device. To access data on the local device, leave this component empty. +- **path**: location of the specific resource to access. +- **query**: query parameters. +- **fragment**: subordinate resources to access. + +Example URIs: + +- Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10* +- Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10* + + +> **NOTE** +> +> In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**. + + ## Available APIs **Table 1** Data ability lifecycle APIs @@ -129,7 +154,7 @@ The basic dependency packages include: import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_rdb from '@ohos.data.rdb' - + var urivar = "dataability:///com.ix.DataAbility" var DAHelper = featureAbility.acquireDataAbilityHelper( urivar @@ -283,9 +308,3 @@ The basic dependency packages include: ] ); ``` - -## Samples - -The following sample is provided to help you better understand how to develop Data abilities: - -- [`DataAbility`: Creation and Access of Data Abilities (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility) diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md index 2cbf353e910af8ebb8dff02218331ae97f568e2c..354945ff4e6dcc79f71c8d16693ce660e4270868 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability/fa-formability.md @@ -349,8 +349,3 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) -## Samples - -The following samples are provided to help you better understand how to develop a widget on the FA model: -- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) -- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher) diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability/fa-pageability.md index 7aa76452a3a17c7fd831044b345ffc6a8844e47a..3a2629a79996660f48dfc247b9a560ea1abe09b4 100644 --- a/en/application-dev/ability/fa-pageability.md +++ b/en/application-dev/ability/fa-pageability.md @@ -217,7 +217,3 @@ export default { }, } ``` -## Samples -The following sample is provided to help you better understand how to develop a Page ability: - -- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 72b4542e19a675d3531948e07375d491fb001c63..75a605c39be73f29e1db8cecf988535c5495ee4a 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -134,7 +134,7 @@ You can use either of the following methods to connect to a Service ability: ```javascript import prompt from '@system.prompt' - + let mRemote; function onConnectCallback(element, remote){ console.log('onConnectLocalService onConnectDone element: ' + element); @@ -161,13 +161,13 @@ You can use either of the following methods to connect to a Service ability: }).catch((e) => { console.log('sendRequest error:' + e); }); - + } - + function onDisconnectCallback(element){ console.log('ConnectAbility onDisconnect Callback') } - + function onFailedCallback(code){ console.log('ConnectAbility onFailed Callback') } @@ -196,7 +196,7 @@ You can use either of the following methods to connect to a Service ability: ```javascript import rpc from "@ohos.rpc"; - + let mMyStub; export default { onStart() { @@ -424,9 +424,3 @@ export default { } }; ``` - -## Samples - -The following samples are provided to help you better understand how to develop a Service ability: -- [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility) -- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) diff --git a/en/application-dev/ability/figures/fa-dataability-uri.png b/en/application-dev/ability/figures/fa-dataability-uri.png new file mode 100644 index 0000000000000000000000000000000000000000..d89ada0ee9b2f9f655a6c3d8b0df17d6b1ca9326 Binary files /dev/null and b/en/application-dev/ability/figures/fa-dataability-uri.png differ diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index 011951ac5073aaec023c7c27aad3fe13dd1a7392..5b61bcec4b25312f994ed94362339e601df5cd55 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -317,7 +317,3 @@ struct Index { } } ``` - -## Samples -The following sample is provided to help you better understand how to develop an ability on the stage model: -- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability/stage-call.md index e402454ddf6afd1b1aab71601e52b19d8010b425..aaa9a9918345c52015969245c3bbba3efbb81048 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -247,7 +247,3 @@ try { Logger.error(TAG, `caller release failed with ${error}`) } ``` - -## Samples -The following sample is provided to help you better understand how to develop an ability call in the stage model: -- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) diff --git a/en/application-dev/ability/stage-formextension.md b/en/application-dev/ability/stage-formextension.md index 0a1b17b91cf2be48405e4e9681146f1017ffa93b..1037c88b76370d92a27153b25784327f78fe4ced 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability/stage-formextension.md @@ -358,8 +358,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) - -## Samples - -The following sample is provided to help you better understand how to develop a widget on the stage model: -- [`FormExtAbility`: Stage Model Widget (eTS, JS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility) diff --git a/en/application-dev/ability/stage-serviceextension.md b/en/application-dev/ability/stage-serviceextension.md index c6f6362a727855189a398b6b305312c45e6135b1..0bda2156cdaa3b79c694f399453208ed9a0d13cf 100644 --- a/en/application-dev/ability/stage-serviceextension.md +++ b/en/application-dev/ability/stage-serviceextension.md @@ -50,7 +50,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p onRemoteRequest(code, data, reply, option) { } } - + class ServiceExt extends ServiceExtensionAbility { console.log('onCreate, want:' + want.abilityName); } @@ -69,7 +69,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p } } ``` -## Samples - -The following sample is provided to help you better understand how to develop Service Extension abilities: -- [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 0a69a2e0f79a874def98d2be58d26d6dec0c3874..b43d1961722f6e6265f0a8b649208c1737f05726 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -71,7 +71,3 @@ httpRequest.request( } ); ``` - -## Samples -The following sample is provided to help you better understand how to develop the HTTP data request feature: -- [`Http`: HTTP Data Request (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http) diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 9444946bda64eadb546cfd282e8d5e4e2f670256..15f38e97a75585520cf60534d03a4c1812001716 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.off('close'); }, 30 * 1000); ``` - -## Samples -The following sample is provided to help you better understand how to develop the socket connection feature: -- [`Socket`: Socket Connection (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket) diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index baf12a5741e2186ab57aeb5feb1acb534fa4651a..dde1feb495e9827ab1f0fd1fad903f71acb9cbb3 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca ## Available APIs +For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). + ### Creating a Distributed Data Object Instance Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**. @@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance. **Table 1** API for creating a distributed data object instance | Package| API| Description| | -------- | -------- | -------- | -| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
- **source**: attributes of the **distributedObject** set.
- **DistributedObject**: returns the distributed object created.| +| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
- **source**: attributes of the **distributedObject** set.
- **DistributedObject**: returns the distributed object created.| ### Generating a Session ID @@ -33,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s **Table 3** API for setting a session ID | Class| API| Description| | -------- | -------- | -------- | -| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.
 **sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.
**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| ### Observing Data Changes Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes. **Table 4** APIs for observing data changes of a distributed data object -| Class| API| Description| +| Class| API| Description| | -------- | -------- | -------- | -| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void | Subscribes to data changes.| +| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void | Subscribes to data changes.| | DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void | Unsubscribes from data changes. **Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.| ### Observing Online or Offline Status @@ -67,13 +69,13 @@ The saved data will be released in the following cases: - The application has been uninstalled. - Data is successfully restored. -**Table 6** APIs for saving a distributed data object and revoking the saving +**Table 6** APIs for saving a distributed data object and revoking the saving operation | Class| API| Description| | -------- | -------- | -------- | | DistributedDataObject | save(deviceId: string): Promise<SaveSuccessResponse> | Saves a distributed data object. This API uses a promise to return the result.| | DistributedDataObject| save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void | Saves a distributed data object. This API uses an asynchronous callback to return the result.| -| DistributedDataObject | revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. | -| DistributedDataObject| revokeSave(): Promise<RevokeSaveSuccessResponse> | Revokes the data saving operation. This API uses a promise to return the result. | +| DistributedDataObject | revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result.| +| DistributedDataObject| revokeSave(): Promise<RevokeSaveSuccessResponse> | Revokes the data saving operation. This API uses a promise to return the result.| ## How to Develop @@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni local_object.on("change", this.changeCallback.bind(this)); ``` -6. Modify object attributes.
The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). +6. Modify object attributes.
The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). The sample code is as follows: ```js @@ -205,41 +207,39 @@ The following example shows how to implement a distributed data object synchroni 10. Save a distributed data object and revoke the data saving operation. - Callback - - - ```js - // Save a distributed data object. - local_object.save("local", (result, data)=>{ - console.log("save callback"); - console.info("save sessionId " + data.sessionId); - console.info("save version " + data.version); - console.info("save deviceId " + data.deviceId); - }); - // Revoke the data saving operation. - local_object.revokeSave((result, data) =>{ - console.log("revokeSave callback"); - console.info("revokeSave sessionId " + data.sessionId); - }); - ``` - - Promise - - ```js - // Save a distributed data object. - g_object.save("local").then((result)=>{ - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); - }, (result)=>{ - console.info("save local failed."); - }); - // Revoke the data saving operation. - g_object.revokeSave().then((result)=>{ - console.info("revokeSave success."); - }, (result)=>{ - console.info("revokeSave failed."); - }); - ``` -11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregister all callbacks of this distributed data object. + + ```js + // Save a distributed data object. + local_object.save("local", (result, data)=>{ + console.log("save callback"); + console.info("save sessionId " + data.sessionId); + console.info("save version " + data.version); + console.info("save deviceId " + data.deviceId); + }); + // Revoke the data saving operation. + local_object.revokeSave((result, data) =>{ + console.log("revokeSave callback"); + console.info("revokeSave sessionId " + data.sessionId); + }); + ``` + - Promise + ```js + // Save a distributed data object. + g_object.save("local").then((result)=>{ + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); + }, (result)=>{ + console.info("save local failed."); + }); + // Revoke the data saving operation. + g_object.revokeSave().then((result)=>{ + console.info("revokeSave success."); + }, (result)=>{ + console.info("revokeSave failed."); + }); + ``` +11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object. The sample code is as follows: ```js diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index 309d2a38e4cbcab79a102b809bb9444cf9a8e1ee..c5608c6eabd526c38a87bd3907fba89fb1a11629 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat ## Available APIs +For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). + The table below describes the APIs provided by the OpenHarmony DDS module. **Table 1** APIs provided by the DDS -| Category | API | Description | -| -------- | --- | ----------- | -| Creating a distributed database | createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| -| Obtaining a distributed KV store | getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Obtains the KV store with the specified **Options** and **storeId**. | -| Managing data in a distributed KV store | put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array \| string \| number \| boolean): Promise<void> | Inserts and updates data. | +| Category | API | Description | +| ------------ | ------------- | ------------- | +| Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| +| Obtaining a distributed KV store| getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Obtains the KV store with the specified **Options** and **storeId**.| +| Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array \| string \| number \| boolean): Promise<void> | Inserts and updates data.| | Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | -| Managing data in a distributed KV store | get(key: string, callback: AsyncCallback<Uint8Array \| string \| boolean \| number>): void
get(key: string): Promise<Uint8Array \| string \| boolean \| number> | Queries data. | -| Subscribing to changes in the distributed data | on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void | Subscribes to data changes in the KV store. | -| Synchronizing data across devices | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | +| Managing data in a distributed KV store| get(key: string, callback: AsyncCallback<Uint8Array \| string \| boolean \| number>): void
get(key: string): Promise<Uint8Array \| string \| boolean \| number> | Queries data. | +| Subscribing to changes in the distributed data| on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void | Subscribes to data changes in the KV store.| +| Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | @@ -29,14 +31,13 @@ The table below describes the APIs provided by the OpenHarmony DDS module. The following uses a single KV store as an example to describe the development procedure. 1. Import the distributed data module. - ```js import distributedData from '@ohos.data.distributedData'; ``` 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. - 1. Create a **KvManagerConfig** object based on the application context. - 2. Create a **KvManager** instance. + (1) Create a **KvManagerConfig** object based on the application context. + (2) Create a **KvManager** instance. The sample code is as follows: ```js @@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p ``` 3. Create and obtain a single KV store. - 1. Declare the ID of the single KV store to create. - 2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. + (1) Declare the ID of the single KV store to create. + (2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. The sample code is as follows: ```js @@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p } ``` - > ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
+ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. -4. Subscribe to changes in the distributed data.
+4. Subscribe to changes in the distributed data.
The following is the sample code for subscribing to the data changes of a single KV store: - ```js kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { console.log("dataChange callback call data: " + JSON.stringify(data)); @@ -104,8 +104,8 @@ The following uses a single KV store as an example to describe the development p ``` 5. Write data to the single KV store. - 1. Construct the key and value to be written into the single KV store. - 2. Write key-value pairs into the single KV store. + (1) Construct the key and value to be written into the single KV store. + (2) Write key-value pairs into the single KV store. The following is the sample code for writing key-value pairs of the string type into the single KV store: @@ -126,11 +126,10 @@ The following uses a single KV store as an example to describe the development p ``` 6. Query data in the single KV store. - 1. Construct the key to be queried from the single KV store. - 2. Query data from the single KV store. + (1) Construct the key to be queried from the single KV store. + (2) Query data from the single KV store. The following is the sample code for querying data of the string type from the single KV store: - ```js const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; @@ -178,3 +177,7 @@ The following uses a single KV store as an example to describe the development p } }); ``` +## Samples +The following samples are provided to help you better understand the distributed data development: +- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) +- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData) diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index 36b6878057640f6cf706efec6d9abbbc1e5b2980..b65916cdd157419ef44b821c423a33ce272f9da0 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -1,12 +1,16 @@ # Preferences Development +> **NOTE** +> +> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. + ## When to Use Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs. ## Available APIs -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. +Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md). ### Creating a Preferences Instance @@ -26,7 +30,7 @@ Call the **put()** method to add or modify data in a **Preferences** instance. | Class | API | Description | | ------- | -------------------------------------------------- | ----------------------------------------------- | -| Preferences | put(key: string, value: ValueType): Promise\ | Writes data of the number, string, and Boolean types.| +| Preferences | put(key: string, value: ValueType): Promise\ | Writes data with the value type of number, string, boolean, Array\, Array\, or Array\.| ### Reading Data @@ -36,7 +40,7 @@ Call the **get()** method to read data from a **Preferences** instance. | Class | API | Description | | ------- | ---------------------------------------------------------- | ----------------------------------------------- | -| Preferences | get(key: string, defValue: ValueType): Promise\ | Reads data of the number, string, and Boolean types.| +| Preferences | get(key: string, defValue: ValueType): Promise\ | Obtains data with the value type of number, string, boolean, Array\, Array\, or Array\.| ### Storing Data Persistently @@ -67,7 +71,7 @@ Use the following APIs to delete a **Preferences** instance or data file. | Package | API | Description | | ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ | -| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise; | Deletes a **Preferences** instance from the cache and deletes its file from the device.| +| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\; | Deletes a **Preferences** instance from the cache and deletes its file from the device.| | ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\; | Removes a **Preferences** instance from the memory to release memory. ## How to Develop @@ -91,8 +95,8 @@ Use the following APIs to delete a **Preferences** instance or data file. ```js promise.then((preferences) => { - let getPromise = preferences.put('startup', 'auto') - getPromise.then(() => { + let putPromise = preferences.put('startup', 'auto') + putPromise.then(() => { console.info("Put the value of startup successfully.") }).catch((err) => { console.info("Failed to put the value of startup with err: " + err) diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 7e465b1a13d86a4512a6d0ec693a8f8c248374d8..53bba062801ec1b8bcf1f65cdc4119fa53757f10 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -2,23 +2,25 @@ ## When to Use -On the basis of the SQLite database, the relational database (RDB) allows you to operate data with or without native SQL statements. In OpenHarmony, an RDB is also called RDB store. +A relational database (RDB) store allows you to operate local data with or without native SQL statements based on SQLite. ## Available APIs +For details about RDB APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). + ### Creating or Deleting an RDB Store -The following table describes the APIs available for creating and deleting an RDB store. +The table below describes the APIs available for creating and deleting an RDB store. **Table 1** APIs for creating and deleting an RDB store | API| Description| | -------- | -------- | -|getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | Obtains an RDB store. This method uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| -|getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.| -|deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| -| deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| +|getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void| Obtains an RDB store. This API uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| +|getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: RDB version.| +|deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void> ): void | Deletes an RDB store. This API uses a callback to return the result.
- **context**: context of the application or function.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| +| deleteRdbStore(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**: RDB store to delete.| ### Managing Data in an RDB Store @@ -32,8 +34,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This method uses a callback to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| - | RdbStore | insert(name: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This method uses a promise to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.| + | RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This API uses a callback to return the result.
- **table**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.| + | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating data** @@ -43,8 +45,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| - | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise\ | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.| + | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **predicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| + | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **predicates**: conditions for updating data.| - **Deleting data** @@ -54,8 +56,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows deleted.| - | RdbStore | delete(rdbPredicates: RdbPredicates): Promise\ | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for deleting data.| + | RdbStore | delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.
- **predicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows updated.| + | 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 result.
- **predicates**: conditions for deleting data.| - **Querying data** @@ -68,10 +70,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| - | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This API uses a callback 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.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. 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>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| ### Using Predicates @@ -141,7 +143,7 @@ A result set can be regarded as a row of data in the queried results. It allows ### Setting Distributed Tables ->**CAUTION**
ohos.permission.DISTRIBUTED_DATASYNC is requied for using the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on**, and **off** APIs of **RdbStore**. +>**CAUTION**
ohos.permission.DISTRIBUTED_DATASYNC is required for using the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on**, and **off** APIs of **RdbStore**. **Setting Distributed Tables** @@ -149,8 +151,8 @@ A result set can be regarded as a row of data in the queried results. It allows | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | setDistributedTables(tables: Array\, callback: AsyncCallback\): void | Sets a list of distributed tables. This method uses a callback to return the result.
- **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| -| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets a list of distributed tables. This method uses a promise to return the result.
- **tables**: names of the distributed tables to set.| +| RdbStore | setDistributedTables(tables: Array\, callback: AsyncCallback\): void | Sets a list of distributed tables. This API uses a callback to return the result.
- **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets a list of distributed tables. This 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** @@ -160,8 +162,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | -| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| +| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** @@ -169,8 +171,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback\>): void | Synchronizes data between devices. This method uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This method uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback\>): void | Synchronizes data between devices. This API uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | **Registering an RDB Store Observer** @@ -178,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** @@ -186,75 +188,106 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| +| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| + +### Backing Up and Restoring an RDB Store + +**Backing Up an RDB Store** + +**Table 13** APIs for backing up an RDB store + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore |backup(destName:string, callback: AsyncCallback<void>):void| Backs up an RDB store. This API uses an asynchronous callback to return the result.
- **destName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| +| 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** + +**Table 14** APIs for restoring an RDB store + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore |restore(srcName:string, callback: AsyncCallback<void>):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.
- **srcName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| +| RdbStore |restore(srcName:string): Promise<void>| Restores an RDB store using a backup file. This API uses a promise to return the result.
- **srcName**: name of the RDB backup file.| ## How to Develop 1. Create an RDB store. - 1. Configure the RDB store attributes, including the RDB store name, storage mode, and whether read-only mode is used. - 2. Initialize the table structure and related data in the RDB store. - 3. Create the RDB store. + + (1) Configure the RDB store attributes, including the RDB store name, storage mode, and whether read-only mode is used. + + (2) Initialize the table structure and related data in the RDB store. + + (3) Create an RDB store. The sample code is as follows: - ```js - import data_rdb from '@ohos.data.rdb' - - const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIG = {name: "rdbstore.db",} - data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { - rdbStore.executeSql(CREATE_TABLE_TEST) - console.info('create table done.') - }) - ``` + ```js + import data_rdb from '@ohos.data.rdb' + + const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + const STORE_CONFIG = {name: "rdbstore.db",} + data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) + console.info('create table done.') + }) + ``` 2. Insert data. - 1. Create a **ValuesBucket** to store the data you need to insert. - 2. Call the **insert()** method to insert data into the RDB store. + + (1) Create a **ValuesBucket** to store the data you need to insert. + + (2) Call the **insert()** method to insert data into the RDB store. The sample code is as follows: - ```js - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} - let insertPromise = rdbStore.insert("test", valueBucket) - ``` + ```js + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} + let insertPromise = rdbStore.insert("test", valueBucket) + ``` 3. Query data. - 1. Create an **RdbPredicates** object to specify query conditions. - 2. Call the **query()** method to query data. - 3. Call the **ResultSet()** method to obtain the query result. + + (1) Create an **RdbPredicates** object to specify query conditions. + + (2) Call the **query()** API to query data. + + (3) Call the **resultSet()** API to obtain the result. The sample code is as follows: - ```js - 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() - }) + ```js + 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() + }) ``` 4. Set the distributed tables to be synchronized. - - 1. Add the following permission to the permission configuration file: + + (1) Add the following permission to the permission configuration file: + ```js "requestPermissions": { "name": "ohos.permission.DISTRIBUTED_DATASYNC" } ``` - 2. Obtain the required permission. - 3. Set the distributed tables. - 4. Check whether the setting is successful. + + (2) Obtain the required permissions. + + (3) Set the distributed tables. + + (4) Check whether the setting is successful. The sample code is as follows: @@ -272,16 +305,19 @@ You can obtain the distributed table name for a remote device based on the local ``` 5. Synchronize data across devices. - 1. Constructs an **RdbPredicates** object to specify remote devices within the network to be synchronized. - 2. Call the **sync()** method to synchronize data. - 3. Check whether data synchronization is successful. + + (1) Construct an **RdbPredicates** object to specify remote devices within the network to be synchronized. + + (2) Call **rdbStore.sync()** to synchronize data. + + (3) Check whether the data synchronization is successful. The sample code is as follows: ```js let predicate = new data_rdb.RdbPredicates('test') predicate.inDevices(['12345678abcde']) - let promise = rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicate) + 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++) { @@ -293,8 +329,10 @@ You can obtain the distributed table name for a remote device based on the local ``` 6. Subscribe to distributed data. - 1. Register an observer to listen for distributed data changes. - 2. When data in the RDB store changes, a callback will be invoked to return the data changes. + + (1) Register an observer to listen for distributed data changes. + + (2) When data in the RDB store changes, a callback will be invoked to return the data changes. The sample code is as follows: @@ -305,15 +343,17 @@ You can obtain the distributed table name for a remote device based on the local } } try { - rdbStore.on('dataChange', rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { console.log('register observer failed') } ``` 7. Query data across devices. - 1. Obtain the distributed table name for a remote device based on the local table name. - 2. Call the **ResultSet()** method to obtain the query result. + + (1) Obtain the distributed table name for a remote device based on the local table name. + + (2) Call the resultSet() API to obtain the result. The sample code is as follows: @@ -321,6 +361,32 @@ You can obtain the distributed table name for a remote device based on the local let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` + +8. Back up and restore an RDB store. + + (1) Back up the current RDB store. + + (2) Restore the RDB store using the backup file. + + The sample code is as follows: + + ```js + let promiseBackup = rdbStore.backup("dbBackup.db") + promiseBackup.then(()=>{ + console.info('Backup success.') + }).catch((err)=>{ + console.info('Backup failed, err: ' + err) + }) + ``` + ```js + let promiseRestore = rdbStore.restore("dbBackup.db") + promiseRestore.then(()=>{ + console.info('Restore success.') + }).catch((err)=>{ + console.info('Restore failed, err: ' + err) + }) + ``` + ## Samples The following samples are provided for you to better understand the RDB development: - [`Rdb`: eTS RDB (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb) diff --git a/en/application-dev/device/device-location-geocoding.md b/en/application-dev/device/device-location-geocoding.md index cfb2504ff30266bdba5699b44f5f0577cc953ea9..30f647d98a368168ba945e11f11bb59f65a5b455 100644 --- a/en/application-dev/device/device-location-geocoding.md +++ b/en/application-dev/device/device-location-geocoding.md @@ -16,17 +16,18 @@ The following table describes APIs available for mutual conversion between coord | API | Description | | -------- | -------- | -| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. | -| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. | -| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. | -| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. | +| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. | +| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. | +| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. | +| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. | +| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. | +| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. | ## How to Develop -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> > The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network. 1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. @@ -45,7 +46,7 @@ The following table describes APIs available for mutual conversion between coord }); ``` - Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see the _API Reference_. + Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). - Call **getAddressesFromLocationName** to convert geographic description into coordinates. ``` @@ -55,6 +56,6 @@ The following table describes APIs available for mutual conversion between coord }); ``` - Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see the _API Reference_. + Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**. diff --git a/en/application-dev/device/sensor-guidelines.md b/en/application-dev/device/sensor-guidelines.md index ca434c9639e064dda463873dee8fdf701271181b..99c6cc6c045a6f7d9a813372af163ab1eaa2efe1 100644 --- a/en/application-dev/device/sensor-guidelines.md +++ b/en/application-dev/device/sensor-guidelines.md @@ -34,40 +34,52 @@ 1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file. ``` - "reqPermissions":[ - { - "name":"ohos.permission.ACCELEROMETER", - "reason"":"", - "usedScene":{ - "ability": ["sensor.index.MainAbility",".MainAbility"], - "when":"inuse" - } - }, - { - "name":"ohos.permission.GYROSCOPE", - "reason"":"", - "usedScene":{ - "ability": ["sensor.index.MainAbility",".MainAbility"], - "when":"inuse" - } - }, - { - "name":"ohos.permission.ACTIVITY_MOTION", - "reason"":"ACTIVITY_MOTION_TEST", - "usedScene":{ - "ability": ["sensor.index.MainAbility",".MainAbility"], - "when":"inuse" - } - }, - { - "name":"ohos.permission.READ_HEALTH_DATA", - "reason"":"HEALTH_DATA_TEST", - "usedScene":{ - "ability": ["sensor.index.MainAbility",".MainAbility"], - "when":"inuse" - } - }, - ] + "reqPermissions": [ + { + "name": "ohos.permission.ACCELEROMETER", + "reason": "", + "usedScene": { + "ability": [ + "sensor.index.MainAbility", + ".MainAbility" + ], + "when": "inuse" + } + }, + { + "name": "ohos.permission.GYROSCOPE", + "reason": "", + "usedScene": { + "ability": [ + "sensor.index.MainAbility", + ".MainAbility" + ], + "when": "inuse" + } + }, + { + "name": "ohos.permission.ACTIVITY_MOTION", + "reason": "ACTIVITY_MOTION_TEST", + "usedScene": { + "ability": [ + "sensor.index.MainAbility", + ".MainAbility" + ], + "when": "inuse" + } + }, + { + "name": "ohos.permission.READ_HEALTH_DATA", + "reason": "HEALTH_DATA_TEST", + "usedScene": { + "ability": [ + "sensor.index.MainAbility", + ".MainAbility" + ], + "when": "inuse" + } + } + ] ``` 2. Subscribe to data changes of a type of sensor. @@ -75,7 +87,7 @@ ``` import sensor from "@ohos.sensor" sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){ - console.info("Subscription succeeded. data = "+ data); // The call is successful, and the obtained sensor data is printed. + console.info("Subscription succeeded. data = " + data); // The call is successful, and the obtained sensor data is printed. } ); ``` @@ -123,8 +135,3 @@ console.error(error); } ``` -## Samples - -The following sample is provided to help you better understand how to develop sensors: - -- [`Sensor`: sensor (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor) diff --git a/en/application-dev/device/sensor-overview.md b/en/application-dev/device/sensor-overview.md index 9951378ea182f7e7bf5635cd7a7bf963a03a6205..ec2374fbdf0fe63d1e10cbf26beff696c899025b 100644 --- a/en/application-dev/device/sensor-overview.md +++ b/en/application-dev/device/sensor-overview.md @@ -1,34 +1,34 @@ # Sensor Overview -Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the APIs provided by sensors, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. +Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the [Sensor](../reference/apis/js-apis-sensor.md) APIs, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows: -| Type | Name | Description | Usage | -| --------------------------------------- | ------------------ | ------------------------------------------------------------ | ---------------------------------------- | -| SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Detecting the motion status | -| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Measuring the acceleration bias estimation | -| SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Detecting the linear acceleration in each axis | -| SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Measuring the gravity | -| SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity | -| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity | -| SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device | -| SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step | -| SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked | -| SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature | -| SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass | -| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation | -| SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity | -| SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar. | Measuring the barometric pressure | -| SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad.| Providing the three orientation angles of the screen | -| SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor.| Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system | -| SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call | -| SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top| -| SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data | -| SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables | -| SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device | +| Type | Name | Description | Usage | +| --------------------------------------- | --------- | ---------------------------------------- | -------------------- | +| SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Detecting the motion status | +| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Measuring the acceleration bias estimation | +| SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Detecting the linear acceleration in each axis | +| SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s2.| Measuring the gravity | +| SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity | +| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity | +| SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device | +| SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step | +| SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked | +| SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature | +| SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass | +| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation | +| SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity | +| SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar.| Measuring the barometric pressure | +| SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad. | Providing the three orientation angles of the screen | +| SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor. | Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system | +| SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call | +| SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top| +| SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data | +| SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables | +| SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device | ## Working Principles @@ -54,12 +54,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso Table 7 Sensor data permissions - | Sensor | Permission | Sensitivity | Permission Description | - | ------------------------- | -------------------------------- | ------------ | ----------------------- | - | Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.| - | Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.| - | Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. | - | Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. | +| Sensor | Permission | Sensitivity | Permission Description | +| ------------------------- | -------------------------------- | ------------ | ----------------------- | +| Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.| +| Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.| +| Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. | +| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. | diff --git a/en/application-dev/device/vibrator-guidelines.md b/en/application-dev/device/vibrator-guidelines.md index b8d201c22ed514ca0047b73b50e9f2184cf0587c..ab4c8234ba4147008ea9515d20e23506eddd3f13 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -5,17 +5,19 @@ You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls. +For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md). + ## Available APIs | Module | API | Description | | ------------- | ---------------------------------------- | ------------------------------- | -| ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result. | -| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result. | -| ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result. | -| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| -| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result. | -| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result. | +| ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result. | +| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result. | +| ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result. | +| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| +| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result. | +| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result. | ## How to Develop @@ -24,36 +26,36 @@ You can set different vibration effects as needed, for example, customizing the ``` "reqPermissions": [ - { - "name": "ohos.permission.ACCELEROMETER", - "reason": "", - "usedScene": { - "ability": [ - ".MainAbility" - ], - "when": "inuse" - } - }, - { - "name": "ohos.permission.VIBRATE", - "reason": "", - "usedScene": { - "ability": [ - ".MainAbility" - ], - "when": "inuse" - } - }, - { - "name": "ohos.permission.ACTIVITY_MOTION", - "reason": "", - "usedScene": { - "ability": [ - ".MainAbility" - ], - "when": "inuse" - } - }, + { + "name": "ohos.permission.ACCELEROMETER", + "reason": "", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "inuse" + } + }, + { + "name": "ohos.permission.VIBRATE", + "reason": "", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "inuse" + } + }, + { + "name": "ohos.permission.ACTIVITY_MOTION", + "reason": "", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "inuse" + } + }, ] ``` @@ -61,12 +63,12 @@ You can set different vibration effects as needed, for example, customizing the ``` import vibrator from "@ohos.vibrator" - vibrator.vibrate(1000).then((error)=>{ - if (error){ // The call fails, and error.code and error.message are printed. - Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); - }else{ // The call is successful, and the device starts to vibrate. + vibrator.vibrate(1000).then((error) => { + if (error) { // The call fails, and error.code and error.message are printed. + Console.log("Promise return failed.error.code " + error.code + "error.message " + error.message); + } else { // The call is successful, and the device starts to vibrate. Console.log("Promise returned to indicate a successful vibration.") - }; + } }) ``` @@ -74,17 +76,11 @@ You can set different vibration effects as needed, for example, customizing the ``` import vibrator from "@ohos.vibrator" - vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ - if(error){ // The call fails, and error.code and error.message are printed. - Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); - }else{ // The call is successful, and the device stops vibrating. + vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => { + if (error) { // The call fails, and error.code and error.message are printed. + Console.log("Promise return failed.error.code " + error.code + "error.message " + error.message); + } else { // The call is successful, and the device stops vibrating. Console.log("Promise returned to indicate a successful stop."); - }; + } }) ``` - -## Samples - -The following sample is provided to help you better understand how to develop vibrators: - -- [`Vibrator`: vibrator (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Vibrator) diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index 06b61fb2e8e733f0762e0f1f5ddae9ea81344396..b8c6422a63e1f3fb8bd012a3e4175de1da055d8f 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -9,3 +9,5 @@ - Distributed Call Chain Tracing - [Overview of Distributed Call Chain Tracing](hitracechain-overview.md) - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) +- Error Management + - [Development of Error Manager](errormanager-guidelines.md) diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..835a6ab9ce3c0beacd19f7c76f5a1eec68bf36cd --- /dev/null +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -0,0 +1,90 @@ +# Development of Error Manager + +## When to Use + +If coding specification issues or errors exist in the code of an application, the application may encounter unexpected errors, for example, uncaught exceptions or application lifecycle timeouts, while it is running. In such a case, the application may exit unexpectedly. Error logs, however, are usually stored on users' local storage, making it inconvenient to locate faults. With the APIs provided by the **errorManager** module, your application will be able to report related errors and logs to your service platform for fault locating before it exits. + +## Available APIs + +Application error management APIs are provided by the **errorManager** module. For details about how to import the module to use related APIs, see [Development Example](#development-example). + +**Table 1** Description of application error management APIs + +| API | Description | +| ------------------------------------------------------------ | ---------------------------------------------------- | +| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.| +| unregisterErrorObserver(observerId: number, callback: AsyncCallback\): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. | +| unregisterErrorObserver(observerId: number): Promise\ | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. | + +When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer). + + +**Table 2** Description of the ErrorObserver API + +| API | Description | +| ------------------------------ | ------------------------------------------------------------ | +| onUnhandledException(errMsg: string): void | Called when an application generates an uncaught exception after being registered.| + + +### Result Codes for Unregistering an Observer + +| Result Code| Description | +| ------ | --------------------------- | +| 0 | Normal. | +| -1 | Input number not exist. | +| -2 | Invalid parameter. | + +## Development Example +```ts +import Ability from '@ohos.application.Ability' +import errorManager from '@ohos.application.errorManager' + +var registerId = -1; +var callback = { + onUnhandledException: function (errMsg) { + console.log(errMsg); + } +} +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[Demo] MainAbility onCreate") + globalThis.abilityWant = want; + } + + onDestroy() { + console.log("[Demo] MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // Main window is created for this ability. + console.log("[Demo] MainAbility onWindowStageCreate") + + globalThis.registerObserver = (() => { + registerId = errorManager.registerErrorObserver(callback); + }) + + globalThis.unRegisterObserver = (() => { + errorManager.unregisterErrorObserver(registerId, (result) => { + console.log("[Demo] result " + result.code + ";" + result.message) + }); + }) + + windowStage.setUIContent(this.context, "pages/index", null) + } + + onWindowStageDestroy() { + // Main window is destroyed to release UI resources. + console.log("[Demo] MainAbility onWindowStageDestroy") + } + + onForeground() { + // Ability is brought to the foreground. + console.log("[Demo] MainAbility onForeground") + } + + onBackground() { + // Ability is brought back to the background. + console.log("[Demo] MainAbility onBackground") + } +}; +``` diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index ee553b735fb510d78ee6531e0a8a71fa99fc53bb..e1d4cddeb2ff96c8a07a6df84382ad0b8d22464c 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -88,9 +88,3 @@ In this example, an application event is logged after the application startup ex ``` 2. Tap the run button on the application UI to run the project. - -## Samples - -The following sample is provided to help you better understand how to develop the application event logging feature: - -- [`JsDotTest`: Event Logging Test (JavaScript) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest) diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 244734770314757986733edc03b597894aa8e75e..66b002200fc1c1965f1d3e741739685ae97236e6 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -1,6 +1,7 @@ -# Internationalization Development (i18n) +# Internationalization Development (I18N) -This development guide describes how to use i18n APIs that are not defined in ECMA 402. +This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402. +The [Intl](intl-guidelines.md) module provides basic I18N capabilities through the standard I18N interfaces defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. ## Obtaining System Language and Region Information diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 9eceb50b876b05c960518ff554f65ec09963c0c9..09bc3b733346db921cd04b76aff04b41d60af0b9 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -1,6 +1,7 @@ -# Internationalization Development (intl) +# Internationalization Development (Intl) -This development guide describes how to use i18n APIs that are defined in ECMA 402. +This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402. +The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. > **NOTE**
> In the code snippets in this document, **intl** refers to the name of the imported module. @@ -49,21 +50,21 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc 2. Obtain the string representing a **Locale** object.
Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. - + ``` var localeStr = localeObj.toString(); ``` 3. Maximize locale information.
Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. - + ``` var maximizedLocale = localeObj.maximize(); ``` 4. Minimize locale information.
Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. - + ``` var minimizedLocale = localeObj.minimize(); ``` @@ -104,7 +105,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date 2. Format the date and time.
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. - + ``` Date date = new Date(); var formatResult = dateTimeFormat.format(date); @@ -112,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date 3. Format a period.
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. - + ``` Date startDate = new Date(); Date endDate = new Date(); @@ -121,7 +122,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date 4. Obtain attributes of the **DateTimeFormat** object.
Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. - + ``` var options = dateTimeFormat.resolvedOptions(); ``` @@ -161,7 +162,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for 2. Format a number.
Call the **format** method to format a number. A string is returned as the formatting result. - + ``` var number = 1234.5678 var formatResult = numberFormat.format(number); @@ -169,7 +170,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for 3. Obtain attributes of the **NumberFormat** object.
Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. - + ``` var options = numberFormat.resolvedOptions(); ``` @@ -208,7 +209,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on 2. Compare two strings.
Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. - + ``` var str1 = "first string"; var str2 = "second string"; @@ -217,7 +218,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on 3. Obtain attributes of the **Collator** object.
Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. - + ``` var options = collator.resolvedOptions(); ``` @@ -255,7 +256,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu 2. Determine the singular-plural type.
Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. - + ``` var number = 1234.5678 var categoryResult = plurals.select(number); @@ -296,7 +297,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r 2. Format the relative time.
Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. - + ``` var number = 2; var unit = "year" @@ -305,7 +306,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r 3. Obtain each part of the relative time format.
Upon obtaining each part of the relative time format, customize the relative time formatting result. - + ``` var number = 2; var unit = "year" @@ -314,13 +315,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r 4. Obtain attributes of the **RelativeTimeFormat** object.
Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md). - + ``` var options = numberFormat.resolvedOptions(); ``` - -## Samples - -The following sample is provided to help you better understand how to develop internationalization capabilities: - --[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/UI/International) diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md index c42fd8cdfe9f24f7040ce8e52268a15bfced04fb..b9f7b63d5b451da5213a8c282d52865d48c4e3eb 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -9,14 +9,15 @@ - [Audio Capture Development](audio-capturer.md) - [OpenSL ES Audio Playback Development](opensles-playback.md) - [OpenSL ES Audio Recording Development](opensles-capture.md) - + - [Audio Interruption Mode Development](audio-interruptmode.md) + - Video - [Video Playback Development](video-playback.md) - [Video Recording Development](video-recorder.md) - + - Image - [Image Development](image.md) - + - Camera - [Camera Development](camera.md) diff --git a/en/application-dev/media/audio-interruptmode.md b/en/application-dev/media/audio-interruptmode.md new file mode 100644 index 0000000000000000000000000000000000000000..9f9355f68c326ec9b6ae8140a6579114bfaefcc3 --- /dev/null +++ b/en/application-dev/media/audio-interruptmode.md @@ -0,0 +1,54 @@ +# Audio Interruption Mode Development + +## When to Use +The audio interruption mode is used to control the playback of multiple audio streams.
+Audio applications can set the audio interruption mode to independent or shared under **AudioRenderer**.
+In shared mode, multiple audio streams share one session ID. In independent mode, each audio stream has an independent session ID. + +### Asynchronous Operations + +To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. + +## How to Develop + +For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). + + +1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
+ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**.
+ This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
+ + ```js + import audio from '@ohos.multimedia.audio'; + + var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 + } + + var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + ``` + +2. Set the audio interruption mode. + + After the **AudioRenderer** instance is initialized, you can set the audio interruption mode.
+ + ```js + var mode_ = audio.InterruptMode.SHARE_MODE; + await this.audioRenderer.setInterruptMode(mode_).then(()=>{ + console.log('[JSAR] [SetInterruptMode] Setting: '+ (mode_ == 0? " share mode":"independent mode") + "success"); + }); + ``` diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index cabf6a85c3638656585ff7e315701408c12467bc..2b0f260908c9e2986269601e588659ce6ce119fc 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -39,36 +39,36 @@ function printfDescription(obj) { // Set the player callbacks. function setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // The play() API can be invoked only after the dataLoad event callback is complete. The play event callback is then triggered. + audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. }); - audioPlayer.on('play', () => { // Set the play event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); - audioPlayer.pause(); // Trigger the pause event callback and pause the playback. + audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. }); - audioPlayer.on('pause', () => { // Set the pause event callback. + audioPlayer.on('pause', () => { // Set the 'pause' event callback. console.info('audio pause success'); - audioPlayer.seek(5000); // Trigger the timeUpdate event callback, and seek to 5000 ms for playback. + audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. }); - audioPlayer.on('stop', () => { // Set the stop event callback. + audioPlayer.on('stop', () => { // Set the 'stop' event callback. console.info('audio stop success'); - audioPlayer.reset(); // Trigger the reset event callback, and reconfigure the src attribute to switch to the next song. + audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. }); - audioPlayer.on('reset', () => { // Set the reset event callback. + audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio reset success'); - audioPlayer.release(); // Release the AudioPlayer resources. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); - audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the timeUpdate event callback. + audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. if (typeof(seekDoneTime) == 'undefined') { console.info('audio seek fail'); return; } console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); // Trigger the volumeChange event callback. + audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. }); - audioPlayer.on('volumeChange', () => { // Set the volumeChange event callback. + audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. console.info('audio volumeChange success'); audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. if (typeof (arrlist) != 'undefined') { @@ -78,13 +78,13 @@ function setCallBack(audioPlayer) { } else { console.log(`audio getTrackDescription fail, error:${error.message}`); } - audioPlayer.stop(); // Trigger the stop event callback to stop the playback. + audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback. }); }); - audioPlayer.on('finish', () => { // Set the finish event callback, which is triggered when the playback is complete. + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); }); - audioPlayer.on('error', (error) => { // Set the error event callback. + audioPlayer.on('error', (error) => { // Set the 'error' event callback. console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); @@ -107,7 +107,7 @@ async function audioPlayerDemo() { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } ``` @@ -119,16 +119,16 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the play event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); }); - audioPlayer.on('finish', () => { // Set the finish event callback, which is triggered when the playback is complete. + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); - audioPlayer.release(); // Release the AudioPlayer resources. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); } @@ -147,7 +147,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } } ``` @@ -161,15 +161,15 @@ export class AudioDemo { // Set the player callbacks. private isNextMusic = false; setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the play event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); - audioPlayer.reset(); // Call the reset() API and trigger the reset event callback. + audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. }); - audioPlayer.on('reset', () => { // Set the reset event callback. + audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio play success'); if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. this.nextMusic(audioPlayer); // Changing songs is implemented. @@ -193,7 +193,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = nextFdPath; // Set the src attribute and trigger the dataLoad event callback. + audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } async audioPlayerDemo() { @@ -210,7 +210,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } } ``` @@ -223,12 +223,12 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); audioPlayer.loop = true; // Set the loop playback attribute. - audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Sets the play event callback to start loop playback. + audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback. console.info('audio play success'); }); } @@ -247,17 +247,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } } ``` - -## Samples - -The following samples are provided to help you better understand how to develop audio playback: - -- [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer) -- [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) -- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) -- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) - diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md index fa43dff19c7488520dd459d53ae326739cdb0fef..6fb1c28efa8bd8bd69e16b09cd577ec4bdeff6e6 100644 --- a/en/application-dev/media/audio-recorder.md +++ b/en/application-dev/media/audio-recorder.md @@ -186,12 +186,3 @@ export class AudioRecorderDemo { } ``` -## Samples - -The following samples are provided to help you better understand how to develop audio recording: - -- [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) -- [`JsRecorder`: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder) -- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) -- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) - diff --git a/en/application-dev/media/image.md b/en/application-dev/media/image.md index cabbd86899cc050a81ee5dba5d834593d6e7b9ee..a262b3e219970b107ee5debdbc1254907f9d3e22 100644 --- a/en/application-dev/media/image.md +++ b/en/application-dev/media/image.md @@ -15,19 +15,19 @@ For details about the APIs, see [Image Processing](../reference/apis/js-apis-ima The full process includes creating an instance, reading image information, reading and writing pixel maps, updating data, packaging pixels, and releasing resources. ```js -const Color = new ArrayBuffer(96); // Create a buffer to store image pixel data. +const color = new ArrayBuffer(96); // Create a buffer to store image pixel data. let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data. // Create a PixelMap object. -const Color = new ArrayBuffer(96); +const color = new ArrayBuffer(96); let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } - image.createPixelMap(Color, opts, pixelmap => { + image.createPixelMap(color, opts, pixelmap => { expect(pixelmap !== null).assertTrue(); console.info('TC_001-1 success'); done(); }) // Read pixels. - pixelmap.readPixels(area,(data) => { +pixelmap.readPixels(area,(data) => { if(data !== null) { var bufferArr = new Uint8Array(area.pixels); var res = true; @@ -50,39 +50,39 @@ pixelmap.readPixelsToBuffer(readBuffer,() => { var bufferArr = new Uint8Array(readBuffer); var res = true; for (var i = 0; i < bufferArr.length; i++) { - if(res) { - if (bufferArr[i] !== 0) { - res = false; - console.info('TC_020-1 Success'); - expect(true).assertTrue(); - done(); - break; - } - } + if(res) { + if (bufferArr[i] !== 0) { + res = false; + console.info('TC_020-1 Success'); + expect(true).assertTrue(); + done(); + break; + } } +} // Write pixels. pixelmap.writePixels(area,() => { const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} - pixelmap.readPixels(readArea,() => { - var readArr = new Uint8Array(readArea.pixels); - var res = true; - for (var i = 0; i < readArr.length; i++) { - if(res) { - if (readArr[i] !== 0) { - res = false; - console.info('TC_022-1 Success'); - expect(true).assertTrue(); - done(); - break; - } - } + pixelmap.readPixels(readArea,() => { + var readArr = new Uint8Array(readArea.pixels); + var res = true; + for (var i = 0; i < readArr.length; i++) { + if(res) { + if (readArr[i] !== 0) { + res = false; + console.info('TC_022-1 Success'); + expect(true).assertTrue(); + done(); + break; + } } + } // Write pixels to the buffer. - pixelmap.writeBufferToPixels(writeColor).then(() => { - const readBuffer = new ArrayBuffer(96); - pixelmap.readPixelsToBuffer(readBuffer).then (() => { +pixelmap.writeBufferToPixels(writeColor).then(() => { + const readBuffer = new ArrayBuffer(96); + pixelmap.readPixelsToBuffer(readBuffer).then (() => { var bufferArr = new Uint8Array(readBuffer); var res = true; for (var i = 0; i < bufferArr.length; i++) { @@ -95,18 +95,18 @@ pixelmap.writePixels(area,() => { break; } } - } + } // Obtain image information. pixelmap.getImageInfo( imageInfo => { - if (imageInfo !== null) { - console.info('TC_024-1 imageInfo is ready'); - expect(imageInfo.size.height == 4).assertTrue(); - expect(imageInfo.size.width == 6).assertTrue(); - expect(imageInfo.pixelFormat == 4).assertTrue(); - done(); - } - }) + if (imageInfo !== null) { + console.info('TC_024-1 imageInfo is ready'); + expect(imageInfo.size.height == 4).assertTrue(); + expect(imageInfo.size.width == 6).assertTrue(); + expect(imageInfo.pixelFormat == 4).assertTrue(); + done(); + } +}) // Release the PixelMap object. pixelmap.release(()=>{ @@ -116,7 +116,7 @@ pixelmap.release(()=>{ }) // Create an image source (uri). -const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.jpg' +const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg' // Create an image source (fd). const imageSourceApi = image.createImageSource(29); @@ -136,7 +136,7 @@ imagePackerApi.packing(imageSourceApi, packOpts, data => { console.info('TC_062-1 finished'); expect(data !== null).assertTrue(); done(); - }) +}) // Release the ImagePacker object. imagePackerApi.release(); @@ -148,7 +148,7 @@ imagePackerApi.release(); /data/local/tmp/test.jpg // Set the path for creating an image source. // Create an image source using a path. -const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.jpg' +const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg' // Set parameters. let decodingOptions = { @@ -171,9 +171,9 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => { // Create a pixel map in promise mode. imageSourceApi.createPixelMap().then(pixelmap => { - console.info('TC_050-11 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); + console.info('TC_050-11 createPixelMap '); + expect(pixelmap !== null ).assertTrue(); + done(); }) // Capture error information when an exception occurs during function invoking. @@ -181,7 +181,7 @@ catch(error => { console.log('TC_050-11 error: ' + error); expect().assertFail(); done(); - }) +}) // Obtain the number of bytes in each line of pixels. pixelmap.getBytesNumberPerRow( num => { @@ -192,13 +192,13 @@ pixelmap.getBytesNumberPerRow( num => { // Obtain the total number of pixel bytes. pixelmap.getPixelBytesNumber(num => { - console.info('TC_026-1 num is ' + num); - expect(num == expectNum).assertTrue(); - done(); - }) + console.info('TC_026-1 num is ' + num); + expect(num == expectNum).assertTrue(); + done(); +}) // Obtain the pixel map information. - pixelmap.getImageInfo( imageInfo => {}) +pixelmap.getImageInfo( imageInfo => {}) // Print the failure information. console.info('TC_024-1 imageInfo is empty'); @@ -206,17 +206,17 @@ expect(false).assertTrue() // Release the PixelMap object. pixelmap.release(()=>{ - expect(true).assertTrue(); - console.log('TC_027-1 suc'); - done(); - }) + expect(true).assertTrue(); + console.log('TC_027-1 suc'); + done(); +}) // Capture release failure information. catch(error => { - console.log('TC_027-1 error: ' + error); - expect().assertFail(); - done(); - }) + console.log('TC_027-1 error: ' + error); + expect().assertFail(); + done(); +}) ``` ### Encoding Scenario @@ -225,14 +225,14 @@ catch(error => { /data/local/tmp/test.png // Set the path for creating an image source. // Set the image source. - const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.png' +const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.png' // Print the error message if the image source fails to be created. if (imageSourceApi == null) { - console.info('TC_062 create image source failed'); - expect(false).assertTrue(); - done(); - } + console.info('TC_062 create image source failed'); + expect(false).assertTrue(); + done(); +} // Create an image packer if the image source is successfully created. const imagePackerApi = image.createImagePacker(); @@ -242,31 +242,58 @@ if (imagePackerApi == null) { console.info('TC_062 create image packer failed'); expect(false).assertTrue(); done(); - } +} // Set encoding parameters if the image packer is successfully created. let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg. - quality:98 }// Image quality, which ranges from 0 to 100. + quality:98 } // Image quality, which ranges from 0 to 100. // Encode the image. imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { - console.info('TC_062 finished'); - expect(data !== null).assertTrue(); - done(); - }) + console.info('TC_062 finished'); + expect(data !== null).assertTrue(); + done(); +}) // Release the image packer after the encoding is complete. - imagePackerApi.release(); - +imagePackerApi.release(); + // Obtain the image source information. imageSourceApi.getImageInfo(imageInfo => { - console.info('TC_045 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); - }) - + console.info('TC_045 imageInfo'); + expect(imageInfo !== null).assertTrue(); + done(); +}) + // Update incremental data. imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {}) ``` + +### Using ImageReceiver + +Example scenario: The camera functions as the client to transmit image data to the server. + +```js +public async init(surfaceId: any) { + + // (Server code) Create an ImageReceiver object. + var receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1); + + // Obtain the surface ID. + var surfaceId = await receiver.getReceivingSurfaceId(); + + // Register a surface listener, which is triggered after the buffer of the surface is ready. + receiver.on('imageArrival', () => { + // Obtain the latest buffer of the surface. + receiver.readNextImage((err, img) => { + img.getComponent(4, (err, component) => { + // Consume component.byteBuffer. For example, save the content in the buffer as an image. + }) + }) + }) + + // Call a Camera API to transfer the surface ID to the camera, which then obtains the surface based on the surface ID and generates a surface buffer. +} +``` diff --git a/en/application-dev/media/opensles-capture.md b/en/application-dev/media/opensles-capture.md index d7aab6606fc0ca49220892e077de2fa5db73ec98..0d0946ca87256f6409a62b81958a2ad784af8161 100644 --- a/en/application-dev/media/opensles-capture.md +++ b/en/application-dev/media/opensles-capture.md @@ -2,10 +2,7 @@ ## When to Use -You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some -[OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented yet is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. - - +You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. ## How to Develop @@ -27,8 +24,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); ``` - - 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. ```c++ @@ -36,8 +31,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf); ``` - - 4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance. ```c++ @@ -81,21 +74,19 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ``` 5. Obtain the **recordItf** instance of the **SL_IID_RECORD** interface. - - ``` + + ```c++ SLRecordItf recordItf; (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf); - ``` + ``` 6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. - ``` + ```c++ SLOHBufferQueueItf bufferQueueItf; (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); ``` - - 7. Register the **BufferQueueCallback** function. ```c++ @@ -120,7 +111,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); ``` - 8. Start audio recording. ```c++ @@ -145,7 +135,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform } ``` - 9. Stop audio recording. ```c++ diff --git a/en/application-dev/media/opensles-playback.md b/en/application-dev/media/opensles-playback.md index f70dc251b831644cccdfdfb9fc6b1dc9ea738965..661bf70ca1551964b05b086d7ec0ab25f46c984d 100644 --- a/en/application-dev/media/opensles-playback.md +++ b/en/application-dev/media/opensles-playback.md @@ -1,13 +1,9 @@ # OpenSL ES Audio Playback Development - - ## When to Use You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. - - ## How to Develop To use OpenSL ES to develop the audio playback function in OpenHarmony, perform the following steps: @@ -20,8 +16,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform #include ``` - - 2. Use the **slCreateEngine** API to obtain an **engine** instance. ```c++ @@ -30,8 +24,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); ``` - - 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. ```c++ @@ -39,8 +31,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); ``` - - 4. Configure the player and create an **AudioPlayer** instance. ```c++ @@ -66,8 +56,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform (*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE); ``` - - 5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. ``` @@ -75,8 +63,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); ``` - - 6. Open an audio file and register the **BufferQueueCallback** function. ```c++ @@ -101,8 +87,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); ``` - - 7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** interface and start playback. ```c++ @@ -111,8 +95,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); ``` - - 8. Stop audio playback. ```c++ diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index 4045cc12c9f198184dce1fd531caa0d783c60ff7..cfc09db79fc853066e03205010f43c2f63c27ce5 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -441,8 +441,3 @@ export class VideoPlayerDemo { } } ``` - -## Samples -The following samples are provided to help you better understand how to develop video playback: - -- [`VideoPlayer`: Video Playback (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/media/VideoPlayer) diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md index f77052fa5ea8e21d48f9a6f11c4636c88483d9c0..6d5b1f04dabf1427a95f24bbc9647221b3a817f5 100644 --- a/en/application-dev/media/video-recorder.md +++ b/en/application-dev/media/video-recorder.md @@ -8,8 +8,6 @@ During video recording, audio and video signals are captured, encoded, and saved ![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) - - **Figure 2** Layer 0 diagram of video recording ![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md index e813f84d92d4155e78c9ca651af6a3e3cd010232..7cbf0e3d9e10bb6d8d346e8f6a9910771c523434 100644 --- a/en/application-dev/napi/drawing-guidelines.md +++ b/en/application-dev/napi/drawing-guidelines.md @@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of double position[2] = {10.0, 15.0}; OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); ``` - -## Samples - -The following samples are provided to help you better understand how to use the Native Drawing module: -* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp) -* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp) diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index e48bcd802e2a1d16536c29193748b14193517e4c..8450f3d8c7f6d0ddfed16215bc8345c2b036c400 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -169,9 +169,3 @@ if (this.subscriber != null) { }) } ``` - -## Samples - -The following sample is provided to help you better understand how to use the common event functionality: - -- [`CommonEvent`: eTS Common Event (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent) diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md index 1a24922a0f7ce6e17e6d65963f13622798348dad..5630462352d721cb3337bfbe302576dc175e29bd 100644 --- a/en/application-dev/notification/notification-guidelines.md +++ b/en/application-dev/notification/notification-guidelines.md @@ -256,10 +256,3 @@ function cancelCallback(err) { Notification.cancel(1, "label", cancelCallback) ``` - - -## Samples - -The following sample is provided to help you better understand how to develop notification functions: - -[`Notification`: EtsNotification (API 8)](https://gitee.com/openharmony/app_samples/tree/master/common/Notification) \ No newline at end of file diff --git a/en/application-dev/quick-start/app-provision-structure.md b/en/application-dev/quick-start/app-provision-structure.md index 0ab67146829dc0d8bed1f6eaac6afb2b06f21854..df74f5fc03327cfa876d0bc329b16ec1f26dc8cb 100644 --- a/en/application-dev/quick-start/app-provision-structure.md +++ b/en/application-dev/quick-start/app-provision-structure.md @@ -4,19 +4,19 @@ The **HarmonyAppProvision** configuration file (also called profile) is the file ## Configuration File Internal Structure The **HarmonyAppProvision** file consists of several parts, which are described in the table below. -**Table 1** Configuration file internal structure -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +**Table 1** Internal structure of the HarmonyAppProvision file +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- | -| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes | No | -| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes | No| -| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No| -| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) and **release** (for application release). The recommended value is **debug**.| String | Yes | No| -| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes | No| +| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes| No | +| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes| No| +| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes| No| +| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes| No| +| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes| No| | validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No | -| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes | No | -| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | No | -| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | No | -| debug-info | Additional debug information. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | No | +| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes| No | +| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No| No | +| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No| No | +| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No| No | An example of the **HarmonyAppProvision** file is as follows: ```json @@ -54,46 +54,46 @@ An example of the **HarmonyAppProvision** file is as follows: ### Internal Structure of the validity Object -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ---------- | ------------------------------- | ------- | ------- | --------- | -| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | -| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | +| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | +| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | ### Internal Structure of the bundle-info Object -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | -------- | --------- | -| developer-id | Unique ID of the developer.| String | Yes | No | -| development-certificate | Information about the [debug certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | -| distribution-certificate | Information about the [release certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise | No | -| bundle-name | Bundle name of the application.| String | Yes | No | -| apl | [Ability privilege level (APL)](../security/accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No | -| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (non-system application).| String | Yes | No | +| developer-id | Unique ID of the developer.| String | Yes| No | +| development-certificate | Information about the [debug certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | +| distribution-certificate | Information about the [release certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No | +| bundle-name | Bundle name of the application.| String | Yes| No | +| apl | [Ability privilege level (APL)](../security/accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes| No | +| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (non-system application).| String | Yes| No | -### Internal structure of the acls Object +### Internal Structure of the acls Object The **acls** object contains the [ACLs](../security/accesstoken-overview.md) configured for your application. It should be noted that you still need to fill the ACL information in the **reqPermissions** attribute in the [config.json](package-structure.md) file. **Table 4** Internal structure of the acls object -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No | No | +| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No| No | ### Internal Structure of the permissions Object The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to fill the permission information in the **reqPermissions** attribute in the [config.json](package-structure.md) file. **Table 5** Internal structure of the permissions object -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No | No | +| restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No| No | ### Internal Structure of the debug-info Object -The **debug-info** object contains debug information of your application, mainly device management and control information. +The **debug-info** object contains debugging information of your application, mainly device management and control information. **Table 6** Internal structure of the debug-info object -| Name | Description | Data Type| Mandatory | Initial Value Allowed| +| Name | Description | Data Type| Mandatory| Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No | -| device-ids | IDs of devices on which your application can be debugged.| String array | No | No | +| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No| No | +| device-ids | IDs of devices on which your application can be debugged.| String array | No| No | diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 5e261f99ad0e2cae3473c8819f10a830fc944954..4646544abd6e22a632a35faeba6184819d601097 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -59,6 +59,7 @@ - Bundle Management - [@ohos.bundle](js-apis-Bundle.md) + - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.zlib](js-apis-zlib.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) @@ -108,6 +109,7 @@ - [@ohos.configPolicy](js-apis-config-policy.md) - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) + - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - Security @@ -173,6 +175,7 @@ - [@ohos.hichecker](js-apis-hichecker.md) - [@ohos.hidebug](js-apis-hidebug.md) - [@ohos.hilog](js-apis-hilog.md) + - [@ohos.hiSysEvent](js-apis-hisysevent.md) - [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - [@ohos.inputMethod](js-apis-inputmethod.md) @@ -192,13 +195,13 @@ - [@ohos.geolocation](js-apis-geolocation.md) - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) + - [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md) - [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md) - [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md) - - [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md) - [@ohos.multimodalInput.keyCode](js-apis-keycode.md) - [@ohos.multimodalInput.keyEvent](js-apis-keyevent.md) - [@ohos.multimodalInput.mouseEvent](js-apis-mouseevent.md) - - [@ohos.multimodalInput.ToucEvent](js-apis-touchevent.md) + - [@ohos.multimodalInput.touchEvent](js-apis-touchevent.md) - [@ohos.power](js-apis-power.md) - [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.sensor](js-apis-sensor.md) diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..5b7866478f7f527ceb806b2aec083bd21835800a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -0,0 +1,48 @@ +# EnterpriseAdminExtentionAbility + +The **EnterpriseAdminExtentionAbility** module provides APIs for Extension abilities of enterprise administrators. + +> **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 of this module can be used only in the stage model. +## Modules to Import + +```ts +import EnterpriseAdminExtentionAbility from '@ohos.EnterpriseAdminExtentionAbility' +``` + +## EnterpriseAdminExtentionAbility.onAdminEnabled + +onAdminEnabled(): void + +Called when an enterprise administrator is enabled. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Example** + + ```ts +export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { + onAdminEnabled() { + } +}; + ``` + +## EnterpriseAdminExtentionAbility.onAdminDisabled + +onAdminDisabled(): void + +Called when an enterprise administrator is disabled. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Example** + + + ```ts +export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { + onAdminDisabled() { + } +}; + ``` diff --git a/en/application-dev/reference/apis/js-apis-abilityManager.md b/en/application-dev/reference/apis/js-apis-abilityManager.md new file mode 100644 index 0000000000000000000000000000000000000000..28c5cd31b0350ca0e8b24c8bfbda21fb039adcd7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-abilityManager.md @@ -0,0 +1,268 @@ +# AbilityManager + +The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. + +> **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. +> The APIs of this module are system APIs and cannot be called by third-party applications. + +# Modules to Import + +```js +import AbilityManager from '@ohos.application.abilityManager' +``` + +## AbilityState + +Enumerates the ability states. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Value| Description| +| -------- | -------- | -------- | +| INITIAL | 0 | The ability is in the initial state.| +| FOREGROUND | 9 | The ability is in the foreground state. | +| BACKGROUND | 10 | The ability is in the background state. | +| FOREGROUNDING | 11 | The ability is in the foregrounding state. | +| BACKGROUNDING | 12 | The ability is in the backgrounding state. | + +## updateConfiguration + +updateConfiguration(config: Configuration, callback: AsyncCallback\): void + +Obtains the ability running information. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | Configuration | Yes | New configuration.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var config = { + language: 'chinese' +} + +abilitymanager.updateConfiguration(config, () => { + console.log('------------ updateConfiguration -----------'); +}) +``` + +## updateConfiguration + +updateConfiguration(config: Configuration): Promise\ + +Updates the configuration. This API uses a promise to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | Configuration | Yes | New configuration.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var config = { + language: 'chinese' +} + +abilitymanager.updateConfiguration(config).then(() => { + console.log('updateConfiguration success'); +}).catch((err) => { + console.log('updateConfiguration fail'); +}) +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(callback: AsyncCallback\>): void + +Obtains the ability running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getAbilityRunningInfos((err,data) => { + console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); +}); +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(): Promise\> + +Obtains the ability running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getAbilityRunningInfos().then((data) => { + console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) +}).catch((err) => { + console.log("getAbilityRunningInfos err: " + err) +}); +``` + +## getExtensionRunningInfos9+ + +getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void + +Obtains the extension running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var upperLimit = 0; + +abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { + console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); +}); +``` + +## getExtensionRunningInfos9+ + +getExtensionRunningInfos(upperLimit: number): Promise\> + +Obtains the extension running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var upperLimit = 0; + +abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { + console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getAbilityRunningInfos err: " + err); +}) +``` + +## getTopAbility9+ + +getTopAbility(callback: AsyncCallback\): void; + +Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getTopAbility((err,data) => { + console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); +}); +``` + +## getTopAbility9+ + +getTopAbility(): Promise\; + +Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\| Promise used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getTopAbility().then((data) => { + console.log("getTopAbility data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getTopAbility err: " + err); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index 2a9c01095ebf3ccfac93d9d96774c103fa2f6e4f..9c1088af3a0fa0c7d15b56f51cdcfa49a9addde9 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -1,6 +1,7 @@ # Animator -> **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. @@ -22,7 +23,7 @@ Creates an **Animator** object. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.| +| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.| **Return value** | Type| Description| @@ -213,6 +214,8 @@ animator.oncancel(); onrepeat: () => void +Called when this animation repeats. + **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** @@ -220,8 +223,6 @@ onrepeat: () => void animator.onrepeat(); ``` -Called when this animation repeats. - ## AnimatorOptions Defines animator options. @@ -231,7 +232,7 @@ Defines animator options. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.| -| easing | string | Yes| Animation interpolation curve. The default value is **ease**.| +| easing | string | Yes| Animation interpolation curve. The default value is **'ease'**.| | delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.| | fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. | | direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.| diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 57d3ad6ddbd25ff75da0532dc83ca2fb7700263b..60f404c4b0510809a4c1d515c3cc99c184796ab9 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -1,6 +1,6 @@ # App Account Management -Provides app account management, including adding, deleting, querying, modifying, and authorizing app accounts, writing data to disks, and synchronizing data. +The **appAccount** module provides APIs for app account management. You can use the APIs to add, delete, query, modify, and authorize app accounts, write data to disks, and synchronize data. > **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. @@ -64,7 +64,7 @@ Adds an app account to the **AppAccountManager** service. This API uses an async addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void -Adds the account name and additional information (information that can be converted into the string type, such as token) of this app to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. +Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -91,7 +91,7 @@ Adds the account name and additional information (information that can be conver addAccount(name: string, extraInfo: string): Promise<void> -Adds the account name and additional information (information that can be converted into the string type, such as token) of this app to the **AppAccountManager** service. This API uses a promise to return the result. +Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -978,7 +978,7 @@ Unsubscribes from the account change events. This API uses an asynchronous callb authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Authenticates an app account to obtain the Open Authorization (OAuth) token. This API uses an asynchronous callback to return the result. +Authenticates an app account to obtain an Open Authorization (OAuth) token. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -986,7 +986,7 @@ Authenticates an app account to obtain the Open Authorization (OAuth) token. Thi | Name | Type | Mandatory | Description | | -------- | --------------------- | ---- | --------------- | -| name | string | Yes | Name of the app account to authenticate. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | authType | string | Yes | Authentication type. | | options | {[key: string]: any} | Yes | Options for the authentication. | @@ -1578,7 +1578,7 @@ Checks whether an app account is authorized to access an app. This API uses an a | Name | Type | Mandatory | Description | | ---------- | ---------------------------- | ----- | ---------------- | | name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to check. | +| bundleName | string | Yes | Bundle name of the app to access.| | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -1604,7 +1604,7 @@ Checks whether an app account is authorized to access an app. This API uses a pr | Name | Type | Mandatory | Description | | ---------- | ------ | ----- | ---------------- | | name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to check. | +| bundleName | string | Yes | Bundle name of the app to access.| **Parameters** @@ -2002,7 +2002,7 @@ Represents the options for setting authenticator properties. | Name | Type | Mandatory | Description | | ---------- | ---------------------- | ----- | -------------- | -| properties | {[key:string]: Object} | No | Authenticator properties to set. | +| properties | {[key:string]: Object} | No | Authenticator properties. | | parameters | {[key:string]: Object} | No | Customized parameters.| ## Constants8+ @@ -2037,7 +2037,7 @@ Enumerates the result codes. | ----------------------------------- | ----- | ------------ | | SUCCESS | 0 | The operation is successful. | | ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | -| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. | +| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The **AppAccountManager** service is abnormal. | | ERROR_INVALID_PASSWORD | 10003 | The password is invalid. | | ERROR_INVALID_REQUEST | 10004 | The request is invalid. | | ERROR_INVALID_RESPONSE | 10005 | The response is invalid. | @@ -2063,7 +2063,7 @@ Provides OAuth authenticator callbacks. onResult: (code: number, result: {[key: string]: any}) => void -Returns the result of an authentication request. +Called to return the result of an authentication request. **System capability**: SystemCapability.Account.AppAccount @@ -2093,7 +2093,7 @@ Returns the result of an authentication request. onRequestRedirected: (request: Want) => void -Redirects a request. +Called to redirect a request. **System capability**: SystemCapability.Account.AppAccount @@ -2126,7 +2126,7 @@ Redirects a request. onRequestContinued: () => void -Continues to process the request. +Called to continue to process the request. **System capability**: SystemCapability.Account.AppAccount @@ -2183,7 +2183,7 @@ Authenticates an app account to obtain the OAuth access token. This API uses an verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; -Verifies the app account credential. This API uses an asynchronous callback to return the result. +Verifies the credential of an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -2191,7 +2191,7 @@ Verifies the app account credential. This API uses an asynchronous callback to r | Name | Type | Mandatory | Description | | ---------------- | --------------------- | ---- | --------------- | | name | string | Yes | Name of the target app account. | -| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Optional for credential verification. | +| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for credential verification. | | callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| ### setProperties9+ diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 87e2238b4c208c14833f7fe00baefd93820209f4..68d01ed3f45885cf6b53fb3de35fc9b3e6c45da5 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,7 +1,6 @@ # Audio Management -> **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 **Audio** module provides basic audio management capabilities, including audio volume and audio device management, and audio data collection and rendering. This module provides the following common audio-related functions: @@ -9,6 +8,10 @@ This module provides the following common audio-related functions: - [AudioRenderer](#audiorenderer8): audio rendering, used to play Pulse Code Modulation (PCM) audio data. - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import ``` @@ -254,7 +257,7 @@ Enumerates the audio interruption modes. | Name | Default Value| Description | | ---------------------------- | ------ | ---------- | -| SHARE_MODE | 0 | Share mode.| +| SHARE_MODE | 0 | Shared mode.| | INDEPENDENT_MODE| 1 | Independent mode. | ## DeviceFlag @@ -578,7 +581,7 @@ Describes the device connection status and device information. | Name | Type | Mandatory| Description | | :---------------- | :------------------------------------------------ | :--- | :----------------- | -| type | [DeviceChangeType](#devicechangetype) | Yes | Device connection status.| +| type | [DeviceChangeType](#devicechangetype) | Yes | Device connection status.| | deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | ## DeviceChangeType @@ -649,6 +652,8 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l Sets the volume for a stream. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -677,6 +682,8 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> Sets the volume for a stream. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1041,6 +1048,8 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void Sets the ringer mode. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + **System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1068,6 +1077,8 @@ setRingerMode(mode: AudioRingMode): Promise<void> Sets the ringer mode. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + **System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1148,6 +1159,8 @@ Sets an audio parameter. This API uses an asynchronous callback to return the re This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS + **System capability**: SystemCapability.Multimedia.Audio.Core **Parameters** @@ -1178,6 +1191,8 @@ Sets an audio parameter. This API uses a promise to return the result. This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS + **System capability**: SystemCapability.Multimedia.Audio.Core **Parameters** @@ -1434,6 +1449,8 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** @@ -1461,6 +1478,8 @@ setMicrophoneMute(mute: boolean): Promise<void> Mutes or unmutes the microphone. This API uses a promise to return the result. +**Required permissions:** ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** @@ -1489,6 +1508,8 @@ isMicrophoneMute(callback: AsyncCallback<boolean>): void Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** @@ -1515,6 +1536,8 @@ isMicrophoneMute(): Promise<boolean> Checks whether the microphone is muted. This API uses a promise to return the result. +**Required permissions**: ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Return value** @@ -1546,7 +1569,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.| +| type | string | Yes | Event type. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.| | callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Example** @@ -1573,7 +1596,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| type | string | Yes | Event type. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.| | callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the updated ringer mode. | **Example** @@ -1596,7 +1619,7 @@ Subscribes to device change events. When a device is connected or disconnected, | Name | Type | Mandatory| Description | | :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Type of event to subscribe to. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| | callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | Yes | Callback used to return the device update details. | **Example** @@ -1622,7 +1645,7 @@ Unsubscribes from device change events. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Type of event to unsubscribe from. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| | callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | No | Callback used to return the device update details. | **Example** @@ -1645,7 +1668,7 @@ Subscribes to audio interruption events. When the application's audio is interru | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| | interrupt | AudioInterrupt | Yes | Audio interruption event type. | | callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | @@ -1681,7 +1704,7 @@ Unsubscribes from audio interruption events. | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to unsubscribe from. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| | interrupt | AudioInterrupt | Yes | Audio interruption event type. | | callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | @@ -2250,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result. ``` import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; +import featureAbility from '@ohos.ability.featureAbility' +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data)=> { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); +var bufferSize; +audioRenderer.getBufferSize().then((data)=> { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); + }); +console.info('Buffer size:'+bufferSize); +var context = featureAbility.getContext(); +var path = await context.getCacheDir(); +var filePath = path+"/StarWars10s-2C-48000-4SW.wav" let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); @@ -2282,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result. ``` import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; +import featureAbility from '@ohos.ability.featureAbility' + +var audioStreamInfo = { + samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels:audio.AudioChannel.CHANNEL_2, + sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 +} +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data) => { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); +var bufferSize; +audioRenderer.getBufferSize().then((data) => { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); + }); +console.info('BufferSize: ' + bufferSize); +var context = featureAbility.getContext(); +var path = await context.getCacheDir(); var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); @@ -2385,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Example** ``` +import audio from '@ohos.multimedia.audio'; +import fileio from '@ohos.fileio'; + +var audioStreamInfo = { + samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels:audio.AudioChannel.CHANNEL_2, + sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data) => { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); var bufferSize; -await audioRenderer.getBufferSize().then(async function (data) => { - console.info('AudioFrameworkRenderLog: getBufferSize :SUCCESS '+data); +audioRenderer.getBufferSize().then((data) => { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); bufferSize=data; }).catch((err) => { - console.info('AudioFrameworkRenderLog: getBufferSize :ERROR : '+err.message); + console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); }); ``` @@ -2519,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to **Example** ``` -audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE).then(() => { +const audioManager = audio.getAudioManager(); +audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE).then(() => { console.log('Promise returned to indicate a successful volume setting.'); }); ``` @@ -2541,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t **Example** ``` -audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE,()=>{ +const audioManager = audio.getAudioManager(); +audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE,()=>{ console.log('Callback returned to indicate a successful volume setting.'); }); ``` @@ -2557,7 +2680,7 @@ Subscribes to audio interruption events. This API uses a callback to get interru | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.| +| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.| | callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | **Example** @@ -2623,7 +2746,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :---------------------------------------- | -| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| | frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | @@ -2631,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th ``` audioRenderer.on('markReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -2650,7 +2773,7 @@ Unsubscribes from mark reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :------------------------------------------------ | -| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **markReach**.| +| type | string | Yes | Event type. The value is fixed at **markReach**.| **Example** @@ -2670,7 +2793,7 @@ Subscribes to period reached events. When the period of frame rendering reaches | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| | frame | number | Yes | Period during which frame rendering is listened. The value must be greater than **0**. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | @@ -2678,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches ``` audioRenderer.on('periodReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -2696,7 +2819,7 @@ Unsubscribes from period reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :-------------------------------------------------- | -| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **periodReach**.| +| type | string | Yes | Event type. The value is fixed at **periodReach**.| **Example** @@ -2716,7 +2839,7 @@ Subscribes to state change events. | Name | Type | Mandatory| Description | | :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| +| type | string | Yes | Event type. The value **stateChange** means the state change event.| | callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** @@ -2912,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result. **Example** ``` +import audio from '@ohos.multimedia.audio'; +import fileio from '@ohos.fileio'; + +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags = 1 +} + +var audioCapturer; +audio.createAudioCapturer(audioCapturerOptions).then((data) => { + audioCapturer = data; + console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message); + }); audioCapturer.start().then(() => { console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); - console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); - console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS '); if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - stateFlag = true; + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); } }).catch((err) => { console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message); @@ -2971,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result. ``` audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped : SUCCESS'); + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - stateFlag=true; - console.info('AudioFrameworkRecLog: resultFlag : '+stateFlag); + console.info('AudioFrameworkRecLog: State is Stopped': '); } }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); - stateFlag=false; + console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); }); ``` @@ -3031,11 +3174,9 @@ audioCapturer.release().then(() => { console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); - stateFlag=true; console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag); }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); - stateFlag=false + console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); }); ``` @@ -3059,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result. **Example** ``` +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message); + }); audioCapturer.read(bufferSize, true, async(err, buffer) => { if (!err) { console.log("Success in reading the buffer data"); @@ -3091,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result. **Example** ``` +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message); + }); +console.info('Buffer size: ' + bufferSize); audioCapturer.read(bufferSize, true).then((buffer) => { console.info('buffer read successfully'); }).catch((err) => { @@ -3194,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Example** ``` -await audioCapturer.getBufferSize().then(async function (bufferSize) { - console.info('AudioFrameworkRecordLog: getBufferSize :SUCCESS '+ bufferSize); - var buffer = await audioCapturer.read(bufferSize, true); - console.info('Buffer read is ' + buffer ); - }).catch((err) => { - console.info('AudioFrameworkRecordLog: getBufferSize :ERROR : '+err.message); +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data); + bufferSize = data; +}).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message); }); ``` @@ -3216,7 +3372,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th | Name | Type | Mandatory| Description | | :------- | :---------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | | frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | | callback | position: number) => {} | Yes | Callback invoked when the event is triggered.| @@ -3224,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th ``` audioCapturer.on('markReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -3242,7 +3398,7 @@ Unsubscribes from mark reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to unsubscribe from. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| **Example** @@ -3262,7 +3418,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| | frame | number | Yes | Period during which frame capturing is listened. The value must be greater than **0**. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | @@ -3270,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th ``` audioCapturer.on('periodReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -3288,7 +3444,7 @@ Unsubscribes from period reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :---------------------------------------------- | -| type | string | Yes | Type of event to unsubscribe from. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| **Example** @@ -3308,7 +3464,7 @@ Subscribes to state change events. | Name | Type | Mandatory| Description | | :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| +| type | string | Yes | Event type. The value **stateChange** means the state change event.| | callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index 1e280124850de1ccfa9658365d97c3219b1d5b2b..5eacfc8a69610d57abec3afdd0fba6f7addaa30b 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -3,7 +3,7 @@ > **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. -Provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. +The Bluetooth module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. ## Modules to Import @@ -201,7 +201,7 @@ Obtains the connection state of a profile. | Name | Type | Mandatory | Description | | --------- | --------- | ---- | ------------------------------------- | -| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| +| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| **Return value** @@ -222,12 +222,12 @@ cancelPairedDevice(deviceId: string): boolean Cancels a paired remote device. +This is a system API. + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory | Description | @@ -388,7 +388,7 @@ startBluetoothDiscovery(): boolean Starts Bluetooth scan to discover remote devices. -**Required permissions**: ohos.permission.USE_BLUETOOTH and ohos.permission.LOCATION +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1039,9 +1039,9 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ## bluetooth.getProfile9+ -getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile +getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile -Obtains a profile instance. **HidHostProfile** is added in API version 9. +Obtains a profile instance. API version 9 is added with **HidHostProfile** and **PanProfile**. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1055,7 +1055,7 @@ Obtains a profile instance. **HidHostProfile** is added in API version 9. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [A2dpSourceProfile](#A2dpSourceProfile), [HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile), or [HidHostProfile](#HidHostProfile) | Profile object obtained. **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, and **HidHostProfile** are supported.| +| [A2dpSourceProfile](#A2dpSourceProfile), [HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile), [HidHostProfile](#HidHostProfile), or [PanProfile](#PanProfile)| Profile instance obtained, which can be **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, **HidHostProfile**, or **PanProfile**.| **Example** @@ -1344,7 +1344,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the remote device to connect.| +| device | string | Yes | Address of the target device.| **Return value** @@ -1374,7 +1374,7 @@ Disconnects an A2DP connection. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the remote device to disconnect.| +| device | string | Yes | Address of the target device.| **Return value** @@ -1422,7 +1422,7 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent); ### off('connectionStateChange')8+ -off(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void Unsubscribes from the A2DP connection state change events. @@ -1451,12 +1451,14 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent); ``` -### getPlayingState +### getPlayingState9+ getPlayingState(device: string): PlayingState Obtains the playing state of a device. +**Required permissions**: ohos.permission.USE_BLUETOOTH + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1576,7 +1578,7 @@ hfpAg.on('connectionStateChange', onReceiveEvent); ### off('connectionStateChange')8+ -off(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void Unsubscribes from the HFP connection state change events. @@ -1616,12 +1618,12 @@ connect(device: string): boolean Connects to the HidHost service of a device. +This is a system API. + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory | Description | @@ -1648,12 +1650,12 @@ disconnect(device: string): boolean Disconnects from the HidHost service of a device. +This is a system API. + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory | Description | @@ -1706,7 +1708,7 @@ hidHost.on('connectionStateChange', onReceiveEvent); ### off('connectionStateChange')9+ -off(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void Unsubscribes from the HidHost connection state change events. @@ -1735,6 +1737,162 @@ hidHost.off('connectionStateChange', onReceiveEvent); ``` +## PanProfile + +Before using a method of **PanProfile**, you need to create an instance of this class by using the **getProfile()** method. + + +### disconnect9+ + +disconnect(device: string): boolean + +Disconnects from the Personal Area Network (PAN) service of a device. + +This is a system API. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX'); +``` + + +### on('connectionStateChange')9+ + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +Subscribes to the PAN connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback used to return the PAN connection state change event. | + +**Return value** + +No value is returned. + +**Example** + +```js +function onReceiveEvent(data) { + console.info('pan state = '+ JSON.stringify(data)); +} +let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +panProfile.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange')9+ + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +Unsubscribes from the PAN connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback used to return the PAN connection state change event. | + +**Return value** + +No value is returned. + +**Example** + +```js +function onReceiveEvent(data) { + console.info('pan state = '+ JSON.stringify(data)); +} +let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +panProfile.on('connectionStateChange', onReceiveEvent); +panProfile.off('connectionStateChange', onReceiveEvent); +``` + + +### setTethering9+ + +setTethering(value: boolean): boolean + +Sets tethering. + +This is a system API. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| value | boolean | Yes | Whether to set tethering over a Bluetooth PAN.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let ret = panProfile.setTethering(true); +``` + + +### isTetheringOn9+ + +isTetheringOn(): boolean + +Obtains the tethering status. + +This is a system API. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| boolean | Returns **true** if tethering is available over a Bluetooth PAN; return **false** otherwise.| + +**Example** + +```js +let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let ret = panProfile.isTetheringOn(); +``` + + ## GattServer Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a **GattServer** instance using the **createGattServer()** method. @@ -1964,6 +2122,15 @@ Notifies the connected client device when a characteristic value changes. **Example** ```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; let arrayBufferC = new ArrayBuffer(8); let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; @@ -2335,6 +2502,7 @@ let gattServer = bluetooth.BLE.createGattServer(); gattServer.off("descriptorWrite"); ``` + ### on('connectStateChange') on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void @@ -2541,14 +2709,9 @@ Obtains all services of the remote BLE device. This API uses a promise to return ```js // Promise -let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); -device.connect(); -var services = device.getServices(); -console.log("bluetooth services size is ", services.length); - -for (let i = 0; i < services.length; i++) { - console.log('bluetooth serviceUuid is ' + services[i].serviceUuid); -} +gattClientDevice.getServices().then(result => { + console.info("Got services successfully:" + JSON.stringify(result)); +}); ``` @@ -2556,7 +2719,7 @@ for (let i = 0; i < services.length; i++) { readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void -Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. +Reads the characteristic value of the specific service of the peer BLE device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2610,7 +2773,7 @@ device.readCharacteristicValue(characteristic, readCcc); readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> -Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result. +Reads the characteristic value of the specific service of the peer BLE device. This API uses a promise to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2657,7 +2820,7 @@ device.readCharacteristicValue(characteristic); readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void -Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. +Reads the descriptor contained in the specific characteristic of the peer BLE device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2701,7 +2864,7 @@ device.readDescriptorValue(descriptor, readDesc); readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> -Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result. +Reads the descriptor contained in the specific characteristic of the peer BLE device. This API uses a promise to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2881,6 +3044,15 @@ Sets the function of notifying the GATT client when the characteristic value of **Example** ```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; let arrayBufferC = new ArrayBuffer(8); let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; @@ -3139,7 +3311,7 @@ Enumerates the scan modes. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Default Value | Description | | ---------------------------------------- | ---- | --------------- | | SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | @@ -3154,7 +3326,7 @@ Enumerates the pairing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Default Value | Description | | ------------------ | ---- | ------ | | BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_BONDING | 1 | Pairing. | @@ -3180,7 +3352,7 @@ Enumerates the SPP link types. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Default Value | Description | | ---------- | ---- | ------------- | | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 02536e5aa2b22f7cc20354e2ac8f56d8bb75421a..74ba45c52450241572aff5ab9cba2a55debd9124 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -42,7 +42,7 @@ Provides the ability information. | labelId | number | Yes | No | Ability label ID. | | subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | | metaData8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability. | -| metaData9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | +| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | | enabled8+ | boolean | Yes | No | Whether the ability is enabled. | | supportWindowMode9+ | Array\<[SupportWindowMode](js-apis-Bundle.md)> | Yes | No | Window modes supported by the ability. | | maxWindowRatio9+ | number | Yes | No | Maximum window ratio supported by the ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index 4f658d8880c014bdbc4cf46cd3ab1d2a7bb01ec0..185338803c92789aea72fa0fca2ab7791ab89ea1 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,42 +1,41 @@ # ApplicationInfo - - -> **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. - - Provides the application information. - +## ApplicationInfo **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------ | -| name | string | Yes | No | Application name. | -| description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | -| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | -| label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | -| icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used.| -| supportedModes | number | Yes | No | Running modes supported by the application. | -| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application. | -| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | -| entryDir | string | Yes | No | Path for storing application files. | -| codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application. | -| metaData9+ | Map\> | Yes | No | Metadata of the application. | -| removable8+ | boolean | Yes | No | Whether the application is removable. | -| accessTokenId8+ | number | Yes | No | Access token ID of the application. | -| uid8+ | number | Yes | No | UID of the application. | -| entityType8+ | string | Yes | No | Entity type of the application. | -| fingerprint9+ | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you apply for for the application. | +| Name | Type | Readable| Writable| Description | +| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Application name. | +| description | string | Yes | No | Application description. | +| descriptionId | number | Yes | No | Application description ID. | +| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | +| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | +| label | string | Yes | No | Application label. | +| labelId | string | Yes | No | Application label ID. | +| icon | string | Yes | No | Application icon. | +| iconId | string | Yes | No | Application icon ID. | +| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | +| supportedModes | number | Yes | No | Running modes supported by the application. | +| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application. | +| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | +| entryDir | string | Yes | No | Path for storing application files. | +| codePath8+ | string | Yes | No | Installation directory of the application. | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application. | +| metadata9+ | Map\> | Yes | No | Metadata of the application. | +| removable8+ | boolean | Yes | No | Whether the application is removable. | +| accessTokenId8+ | number | Yes | No | Access token ID of the application. | +| uid8+ | number | Yes | No | UID of the application. | +| entityType8+ | string | Yes | No | Entity type of the application. | +| fingerprint9+ | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you request for the application.| +| appDistributionType9+ | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**. | +| appProvisionType9+ | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index 38a93fd67cb7cd086f4e2f317dfd9a966ddc1f6d..f9e8ea3be2d7ccfff71426848d2dbc2f0e349201 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -2,14 +2,15 @@ -> **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. Provides the application bundle information. - +## BundleInfo **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md index d45e4620d5af5f29334b9cb4bc264acea124095a..3fc0106cb1ae1317f4edfbffe87675626dfd016b 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md +++ b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @@ -2,14 +2,15 @@ -> **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. Provides custom metadata. - +## CustomizeData **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md new file mode 100644 index 0000000000000000000000000000000000000000..ede83cd6de76637220005f0821471c0141c9721f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -0,0 +1,20 @@ +# ElementName + +> **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. + +Provides the element name information. + +## ElementName + + **System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| deviceId | string | Yes | Yes | Device ID. | +| bundleName | string | Yes | Yes | Bundle name of the application. | +| abilityName | string | Yes | Yes | Name of the ability. | +| uri | string | Yes | Yes | URI. | +| shortName | string | Yes | Yes | Short name of the ability. | +| moduleName9+ | string | Yes | Yes | Name of the HAP file to which the ability belongs. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md index ad3f411f69569eea7a25179302af000f2dee3edb..3c98a25b721a8f3cce41f927d7a35456761db366 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md @@ -2,14 +2,15 @@ -> **NOTE**
+> **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. Provides the Extension ability information. - +## ExtensionAbilityInfo **System capability**: SystemCapability.BundleManager.BundleFramework @@ -25,7 +26,7 @@ Provides the Extension ability information. | extensionAbilityType | bundle.ExtensionAbilityType | Yes | No | Type of the Extension ability. | | permissions | Array\ | Yes | No | Permissions required for other applications to call the Extension ability.| | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the Extension ability. | -| metaData | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. | +| metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. | | enabled | boolean | Yes | No | Whether the Extension ability is enabled. | | readPermission | string | Yes | No | Permission required for reading the Extension ability data. | | writePermission | string | Yes | No | Permission required for writing data to the Extension ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index 89a4a6d8a16ce6e8d1b98a36bfe26df6ca3bf414..2f6dbbef26e41ec1f78fe5768c2389d1a8ee0578 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -2,14 +2,15 @@ -> **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. Provides the HAP module information. - +## HapModuleInfo **System capability**: SystemCapability.BundleManager.BundleFramework @@ -35,4 +36,4 @@ Provides the HAP module information. | mainElementName9+ | string | Yes | No | Information about the main ability. | | extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.| | metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | -| hashValue9+ | string | Yes | No | The hash value of the module. | \ No newline at end of file +| hashValue9+ | string | Yes | No | Hash value of the module. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-Metadata.md b/en/application-dev/reference/apis/js-apis-bundle-Metadata.md index 7c7d43b444284377bb4e80dc201ef45141ece00c..81a2bd77f57ad54be375f6911fe02102b04d20a9 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-Metadata.md +++ b/en/application-dev/reference/apis/js-apis-bundle-Metadata.md @@ -2,14 +2,15 @@ -> **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. +> **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. Provides the metadata information. - +## Metadata **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 71fc24ff40eca2febce360b6be7b9eeb149d1b52..4dc32a18b0aad9b28e8550d9a66b32bf85220add 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -2,14 +2,15 @@ -> **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. Provides the module information of the application. - +## ModuleInfo **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 40a50ebc4aa5ea496d19df951ff04d03240a1b93..3d532293b18ca1b262feabe80615dc1807ac30dc 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -1,6 +1,6 @@ # Performance Tracing -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **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. > - 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. @@ -17,7 +17,7 @@ import bytrace from '@ohos.bytrace'; startTrace(name: string, taskId: number, expectedTime?: number): void -Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. +Marks the start of a timeslice trace task. **System capability**: SystemCapability.Developtools.Bytrace @@ -25,11 +25,12 @@ Starts a trace task. **expectedTime** is an optional parameter, which specifies | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the trace task to start.| -| taskId | number | Yes| Task ID.| +| name | string | Yes| Name of a timeslice trace task.| +| taskId | number | Yes| ID of a timeslice trace task.| | expectedTime | number | No| Expected duration of the trace, in ms.| -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. **Example** @@ -44,7 +45,7 @@ bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is finishTrace(name: string, taskId: number): void -Stops a trace task. +Marks the end of a timeslice trace task. **System capability**: SystemCapability.Developtools.Bytrace @@ -52,10 +53,11 @@ Stops a trace task. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the trace task to start.| -| taskId | number | Yes| Task ID.| +| name | string | Yes| Name of a timeslice trace task.| +| taskId | number | Yes| ID of a timeslice trace task.| -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. **Example** @@ -91,7 +93,7 @@ bytrace.finishTrace("myTestFunc", 1); traceByValue(name: string, count: number): void -Traces the value changes of a variable. +Defines the variable that indicates the number of timeslice trace tasks. **System capability**: SystemCapability.Developtools.Bytrace diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 34b0ab6878da8b7a36848c5f7d7181022009a34b..43f15f6c7b3666fc53f69deadb0043e6adacca46 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -1,18 +1,15 @@ # Camera Management -> **NOTE**
+> **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 -``` +```js import camera from '@ohos.multimedia.camera'; ``` -## Required Permissions - -ohos.permission.CAMERA - ## camera.getCameraManager getCameraManager(context: Context, callback: AsyncCallback): void @@ -30,7 +27,7 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to **Example** -``` +```js camera.getCameraManager(context, (err, cameraManager) => { if (err) { console.error('Failed to get the CameraManager instance ${err.message}'); @@ -62,7 +59,7 @@ Obtains a **CameraManager** instance. This API uses a promise to return the resu **Example** -``` +```js camera.getCameraManager(context).then((cameraManager) => { console.log('Promise returned with the CameraManager instance.'); }) @@ -74,12 +71,12 @@ Enumerates the camera statuses. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ------------------------- | ------ | ------------ | -| CAMERA_STATUS_APPEAR | 0 | The camera exists. | -| CAMERA_STATUS_DISAPPEAR | 1 | The camera does not exist.| -| CAMERA_STATUS_AVAILABLE | 2 | The camera is ready. | -| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is not ready.| +| Name | Value | Description | +| ------------------------- | ---- | ------------ | +| CAMERA_STATUS_APPEAR | 0 | The camera exists. | +| CAMERA_STATUS_DISAPPEAR | 1 | The camera does not exist.| +| CAMERA_STATUS_AVAILABLE | 2 | The camera is ready. | +| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is not ready.| ## CameraPosition @@ -88,11 +85,11 @@ Enumerates the camera positions. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| --------------------------- | ------ | ---------------- | -| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position.| -| CAMERA_POSITION_BACK | 1 | Rear camera. | -| CAMERA_POSITION_FRONT | 2 | Front camera. | +| Name | Value | Description | +| --------------------------- | ---- | ---------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position.| +| CAMERA_POSITION_BACK | 1 | Rear camera. | +| CAMERA_POSITION_FRONT | 2 | Front camera. | ## CameraType @@ -100,13 +97,13 @@ Enumerates the camera types. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ----------------------- | ------ | ---------------- | -| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type.| -| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | -| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | -| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | -| CAMERA_TYPE_TRUE_DEPTH | 4 | True depth camera. | +| Name | Value | Description | +| ----------------------- | ---- | ---------------- | +| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type.| +| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | +| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | +| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | +| CAMERA_TYPE_TRUE_DEPTH | 4 | True depth camera. | ## ConnectionType @@ -115,12 +112,22 @@ Enumerates the camera connection types. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ---------------------------- | ------ | ------------- | -| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | -| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB.| -| CAMERA_CONNECTION_REMOTE | 2 | Remote camera. | +| Name | Value | Description | +| ---------------------------- | ---- | ------------- | +| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | +| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB.| +| CAMERA_CONNECTION_REMOTE | 2 | Remote camera. | + +## Size + +Defines the image size that can be used in previewing, photographing, and video recording. + +**System capability**: SystemCapability.Multimedia.Camera.Core +| Name | Type | Readable| Writable| Description | +| ------ | ------ | ---- | ---- | ------------ | +| height | string | Yes | Yes | Image height.| +| width | number | Yes | Yes | Image width.| ## CameraManager @@ -142,7 +149,7 @@ Obtains all cameras supported by the device. This API uses an asynchronous callb **Example** -``` +```js cameraManager.getCameras((err, cameras) => { if (err) { console.error('Failed to get the cameras. ${err.message}'); @@ -169,41 +176,32 @@ Obtains all cameras supported by the device. This API uses a promise to return t **Example** -``` +```js cameraManager.getCameras().then((cameraArray) => { console.log('Promise returned with an array of supported cameras: ' + cameraArray.length); }) ``` -### Size - -Size parameters. This interface used to get supported size for Preview + Photo + Video. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Default Value | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| height | number | Yes | Desired height of the Preview + Photo + Video. | -| width | number | Yes | Desired width of the Preview + Photo + Video.| - ### createCameraInput createCameraInput(cameraId: string, callback: AsyncCallback): void Creates a **CameraInput** instance with the specified camera ID. This API uses an asynchronous callback to return the instance. +**Required permissions**: ohos.permission.CAMERA + **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Default Value | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ----------------------------------- | | cameraId | string | Yes | Camera ID used to create the instance. | | callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| **Example** -``` +```js cameraManager.createCameraInput(cameraId, (err, cameraInput) => { if (err) { console.error('Failed to create the CameraInput instance. ${err.message}'); @@ -219,11 +217,13 @@ createCameraInput(cameraId: string): Promise Creates a **CameraInput** instance with the specified camera ID. This API uses a promise to return the instance. +**Required permissions**: ohos.permission.CAMERA + **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Default Value| Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------ | | cameraId | string | Yes | Camera ID used to create the instance.| @@ -235,7 +235,7 @@ Creates a **CameraInput** instance with the specified camera ID. This API uses a **Example** -``` +```js cameraManager.createCameraInput(cameraId).then((cameraInput) => { console.log('Promise returned with the CameraInput instance'); }) @@ -247,6 +247,8 @@ createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCal Creates a **CameraInput** instance with the specified camera position and camera type. This API uses an asynchronous callback to return the instance. +**Required permissions**: ohos.permission.CAMERA + **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** @@ -259,7 +261,7 @@ Creates a **CameraInput** instance with the specified camera position and camera **Example** -``` +```js cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { console.error('Failed to create the CameraInput instance. ${err.message}'); @@ -275,6 +277,8 @@ createCameraInput(position: CameraPosition, type: CameraType): Promise { console.log('Promise returned with the CameraInput instance.'); }) @@ -302,7 +306,7 @@ cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, came on(type: 'cameraStatus', callback: AsyncCallback): void -Listens for camera status changes. This API uses a callback to return the camera status changes. +Listens for camera status changes. This API uses an asynchronous callback to return the camera status changes. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -315,7 +319,7 @@ Listens for camera status changes. This API uses a callback to return the camera **Example** -``` +```js cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { if (err) { console.error('Failed to get cameraStatus callback. ${err.message}'); @@ -328,7 +332,7 @@ cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { ## Camera -After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera instance is returned, including camera-related metadata such as **cameraId**, **cameraPosition**, **cameraType**, and **connectionType**. +After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera instance is returned, with camera-related metadata such as **cameraId**, **cameraPosition**, **cameraType**, and **connectionType**. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -341,7 +345,7 @@ After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera **Example** -``` +```js async function getCameraInfo("cameraId") { var cameraManager = await camera.getCameraManager(); var cameras = await cameraManager.getCameras(); @@ -351,7 +355,6 @@ async function getCameraInfo("cameraId") { var cameraType = cameraObj.cameraType; var connectionType = cameraObj.connectionType; } - ``` ## CameraStatusInfo @@ -386,7 +389,7 @@ Obtains the camera ID based on which this **CameraInput** instance is created. T **Example** -``` +```js cameraInput.getCameraId((err, cameraId) => { if (err) { console.error('Failed to get the camera ID. ${err.message}'); @@ -412,7 +415,7 @@ Obtains the camera ID based on which this **CameraInput** instance is created. T **Example** -``` +```js cameraInput.getCameraId().then((cameraId) => { console.log('Promise returned with the camera ID:' + cameraId); }) @@ -435,7 +438,7 @@ Checks whether the device has flash light. This API uses an asynchronous callbac **Example** -``` +```js cameraInput.hasFlash((err, status) => { if (err) { console.error('Failed to check whether the device has flash light. ${err.message}'); @@ -461,7 +464,7 @@ Checks whether the device has flash light. This API uses a promise to return the **Example** -``` +```js cameraInput.hasFlash().then((status) => { console.log('Promise returned with the flash light support status:' + status); }) @@ -484,7 +487,7 @@ Checks whether a specified flash mode is supported. This API uses an asynchronou **Example** -``` +```js cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { if (err) { console.error('Failed to check whether the flash mode is supported. ${err.message}'); @@ -516,7 +519,7 @@ Checks whether a specified flash mode is supported. This API uses a promise to r **Example** -``` +```js cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { console.log('Promise returned with flash mode support status.' + status); }) @@ -544,7 +547,7 @@ Before setting the parameters, do the following checks: **Example** -``` +```js cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { if (err) { console.error('Failed to set the flash mode ${err.message}'); @@ -581,7 +584,7 @@ Before setting the parameters, do the following checks: **Example** -``` +```js cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFlashMode.'); }) @@ -603,7 +606,7 @@ Obtains the current flash mode. This API uses an asynchronous callback to return **Example** -``` +```js cameraInput.getFlashMode((err, flashMode) => { if (err) { console.error('Failed to get the flash mode ${err.message}'); @@ -629,7 +632,7 @@ Obtains the current flash mode. This API uses a promise to return the result. **Example** -``` +```js cameraInput.getFlashMode().then((flashMode) => { console.log('Promise returned with current flash mode : ' + flashMode); }) @@ -652,7 +655,7 @@ Checks whether a specified focus mode is supported. This API uses an asynchronou **Example** -``` +```js cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { if (err) { console.error('Failed to check whether the focus mode is supported. ${err.message}'); @@ -680,11 +683,11 @@ Checks whether a specified focus mode is supported. This API uses a promise to r | Type | Description | | ----------------- | ----------------------------------------------------------- | -| Promise | Promise used to return the flash mode support status. The value **true** means that the specified focus mode is supported.| +| Promise | Promise used to return the focus mode support status. The value **true** means that the specified focus mode is supported.| **Example** -``` +```js cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { console.log('Promise returned with focus mode support status.' + status); }) @@ -709,7 +712,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte **Example** -``` +```js cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { if (err) { console.error('Failed to set the focus mode ${err.message}'); @@ -743,7 +746,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte **Example** -``` +```js cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFocusMode.'); }) @@ -765,7 +768,7 @@ Obtains the current focus mode. This API uses an asynchronous callback to return **Example** -``` +```js cameraInput.getFocusMode((err, afMode) => { if (err) { console.error('Failed to get the focus mode ${err.message}'); @@ -791,7 +794,7 @@ Obtains the current focus mode. This API uses a promise to return the result. **Example** -``` +```js cameraInput.getFocusMode().then((afMode) => { console.log('Promise returned with current focus mode : ' + afMode); }) @@ -813,7 +816,7 @@ Obtains the zoom ratio range. This API uses an asynchronous callback to return t **Example** -``` +```js cameraInput.getZoomRatioRange((err, zoomRatioRange) => { if (err) { console.error('Failed to get the zoom ratio range. ${err.message}'); @@ -839,7 +842,7 @@ Obtains the zoom ratio range. This API uses a promise to return the result. **Example** -``` +```js cameraInput.getZoomRatioRange().then((zoomRatioRange) => { console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); }) @@ -862,7 +865,7 @@ Sets a zoom ratio. This API uses an asynchronous callback to return the result. **Example** -``` +```js cameraInput.setZoomRatio(1, (err) => { if (err) { console.error('Failed to set the zoom ratio value ${err.message}'); @@ -894,7 +897,7 @@ Sets a zoom ratio. This API uses a promise to return the result. **Example** -``` +```js cameraInput.setZoomRatio(1).then(() => { console.log('Promise returned with the successful execution of setZoomRatio.'); }) @@ -916,7 +919,7 @@ Obtains the current zoom ratio. This API uses an asynchronous callback to return **Example** -``` +```js cameraInput.getZoomRatio((err, zoomRatio) => { if (err) { console.error('Failed to get the zoom ratio ${err.message}'); @@ -942,7 +945,7 @@ Obtains the current zoom ratio. This API uses a promise to return the result. **Example** -``` +```js cameraInput.getZoomRatio().then((zoomRatio) => { console.log('Promise returned with current zoom ratio : ' + zoomRatio); }) @@ -964,7 +967,7 @@ Releases this **CameraInput** instance. This API uses an asynchronous callback t **Example** -``` +```js cameraInput.release((err) => { if (err) { console.error('Failed to release the CameraInput instance ${err.message}'); @@ -990,7 +993,7 @@ Releases this **CameraInput** instance. This API uses a promise to return the re **Example** -``` +```js cameraInput.release().then(() => { console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); }) @@ -1000,7 +1003,7 @@ cameraInput.release().then(() => { on(type: 'focusStateChange', callback: AsyncCallback): void -Listens for focus state changes. This API uses a callback to return the focus state changes. +Listens for focus state changes. This API uses an asynchronous callback to return the focus state changes. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1013,7 +1016,7 @@ Listens for focus state changes. This API uses a callback to return the focus st **Example** -``` +```js cameraInput.on('focusStateChange', (focusState) => { console.log('Focus state : ' + focusState); }) @@ -1029,40 +1032,39 @@ Listens for **CameraInput** errors. This API uses a callback to return the error **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------------- | :--- | :---------------------------------------------- | +| Name | Type | Mandatory| Description | +| :------- | :------------------------------- | :--- | :----------------------------------------------- | | type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the camera input error event.| -| callback | ErrorCallback | Yes | Callback used to return the capture input errors. | +| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the error information. | **Example** -``` +```js cameraInput.on('error', (cameraInputError) => { console.log('Camera input error code: ' + cameraInputError.code); }) ``` -## CameraInputErrorCode +## CameraInputErrorCode -Enumerates the CameraInput error code. +Enumerates the **CameraInput** error codes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| ERROR_UNKNOWN | -1 | Unknown error.| +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -## CameraInputError +## CameraInputError -Camera input error object which extends **Error** interface. +Defines a **CameraInput** error object. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** +| Name| Type | Description | +| ---- | ------------------------------------------- | -------------------------- | +| code | [CameraInputErrorCode](#camerainputerrorcode) | **CameraInput** error code.| -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| code | [CameraInputErrorCode](#camerainputerrorcode) | Used to get error code in CameraInput on('error') callback| ## FlashMode @@ -1070,12 +1072,12 @@ Enumerates the flash modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| FLASH_MODE_CLOSE | 0 | The flash is off.| -| FLASH_MODE_OPEN | 1 | The flash is on.| -| FLASH_MODE_AUTO | 2 | The flash mode is auto, indicating that the flash fires automatically depending on the shooting conditions.| -| FLASH_MODE_ALWAYS_OPEN | 3 | The flash is steady on.| +| Name | Value | Description | +| ---------------------- | ---- | ------------ | +| FLASH_MODE_CLOSE | 0 | The flash is off.| +| FLASH_MODE_OPEN | 1 | The flash is on.| +| FLASH_MODE_AUTO | 2 | The flash mode is auto, indicating that the flash fires automatically depending on the shooting conditions.| +| FLASH_MODE_ALWAYS_OPEN | 3 | The flash is steady on.| ## FocusMode @@ -1083,12 +1085,12 @@ Enumerates the focus modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| -------------------------- | ------ | ------------------ | -| FOCUS_MODE_MANUAL | 0 | Manual focus. | -| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.| -| FOCUS_MODE_AUTO | 2 | Auto focus. | -| FOCUS_MODE_LOCKED | 3 | Locked focus. | +| Name | Value | Description | +| -------------------------- | ---- | ------------------ | +| FOCUS_MODE_MANUAL | 0 | Manual focus. | +| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.| +| FOCUS_MODE_AUTO | 2 | Auto focus. | +| FOCUS_MODE_LOCKED | 3 | Locked focus. | ## FocusState @@ -1096,11 +1098,11 @@ Enumerates the focus states. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| --------------------- | ------ | ------------ | -| FOCUS_STATE_SCAN | 0 | Scanning. | -| FOCUS_STATE_FOCUSED | 1 | Focused.| -| FOCUS_STATE_UNFOCUSED | 2 | Unfocused.| +| Name | Value | Description | +| --------------------- | ---- | ------------ | +| FOCUS_STATE_SCAN | 0 | Scanning. | +| FOCUS_STATE_FOCUSED | 1 | Focused.| +| FOCUS_STATE_UNFOCUSED | 2 | Unfocused.| ## camera.createCaptureSession @@ -1119,7 +1121,7 @@ Creates a **CaptureSession** instance. This API uses an asynchronous callback to **Example** -``` +```js camera.createCaptureSession((context), (err, captureSession) => { if (err) { console.error('Failed to create the CaptureSession instance. ${err.message}'); @@ -1151,7 +1153,7 @@ Creates a **CaptureSession** instance. This API uses a promise to return the ins **Example** -``` +```js camera.createCaptureSession(context).then((captureSession) => { console.log('Promise returned with the CaptureSession instance'); }) @@ -1177,7 +1179,7 @@ Starts configuration for this **CaptureSession** instance. This API uses an asyn **Example** -``` +```js captureSession.beginConfig((err) => { if (err) { console.error('Failed to start the configuration. ${err.message}'); @@ -1204,7 +1206,7 @@ Starts configuration for this **CaptureSession** instance. This API uses a promi **Example** -``` +```js captureSession.beginConfig().then(() => { console.log('Promise returned to indicate the begin config success.'); }) @@ -1226,7 +1228,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses an **Example** -``` +```js captureSession.commitConfig((err) => { if (err) { console.error('Failed to commit the configuration. ${err.message}'); @@ -1252,7 +1254,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses a **Example** -``` +```js captureSession.commitConfig().then(() => { console.log('Promise returned to indicate the commit config success.'); }) @@ -1275,7 +1277,7 @@ Adds a **CameraInput** instance to this **CaptureSession** instance. This API us **Example** -``` +```js captureSession.addInput(cameraInput, (err) => { if (err) { console.error('Failed to add the CameraInput instance. ${err.message}'); @@ -1307,7 +1309,7 @@ Adds a **CameraInput** instance to this **CaptureSession** instance. This API us **Example** -``` +```js captureSession.addInput(cameraInput).then(() => { console.log('Promise used to indicate that the CameraInput instance is added.'); }) @@ -1330,7 +1332,7 @@ Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API **Example** -``` +```js captureSession.addOutput(previewOutput, (err) => { if (err) { console.error('Failed to add the PreviewOutput instance ${err.message}'); @@ -1362,7 +1364,7 @@ Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API **Example** -``` +```js captureSession.addOutput(previewOutput).then(() => { console.log('Promise used to indicate that the PreviewOutput instance is added.'); }) @@ -1385,7 +1387,7 @@ Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API us **Example** -``` +```js captureSession.addOutput(photoOutput, (err) => { if (err) { console.error('Failed to add the PhotoOutput instance ${err.message}'); @@ -1417,7 +1419,7 @@ Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API us **Example** -``` +```js captureSession.addOutput(photoOutput).then(() => { console.log('Promise used to indicate that the PhotoOutput instance is added.'); }) @@ -1440,7 +1442,7 @@ Adds a **VideoOutput** instance to this **CaptureSession** instance. This API us **Example** -``` +```js captureSession.addOutput(videoOutput, (err) => { if (err) { console.error('Failed to add the VideoOutput instance ${err.message}'); @@ -1472,7 +1474,7 @@ Adds a **VideoOutput** instance to this **CaptureSession** instance. This API us **Example** -``` +```js captureSession.addOutput(videoOutput).then(() => { console.log('Promise used to indicate that the VideoOutput instance is added.'); }) @@ -1495,7 +1497,7 @@ Removes a **CameraInput** instance from this **CaptureSession** instance. This A **Example** -``` +```js captureSession.removeInput(cameraInput, (err) => { if (err) { console.error('Failed to remove the CameraInput instance. ${err.message}'); @@ -1527,7 +1529,7 @@ Removes a **CameraInput** instance from this **CaptureSession** instance. This A **Example** -``` +```js captureSession.removeInput(cameraInput).then(() => { console.log('Promise returned to indicate that the cameraInput instance is removed.'); }) @@ -1550,7 +1552,7 @@ Removes a **PreviewOutput** instance from this **CaptureSession** instance. This **Example** -``` +```js captureSession.removeOutput(previewOutput, (err) => { if (err) { console.error('Failed to remove the PreviewOutput instance. ${err.message}'); @@ -1584,7 +1586,7 @@ Removes a **PreviewOutput** instance from this **CaptureSession** instance. This **Example** -``` +```js captureSession.removeOutput(previewOutput).then(() => { console.log('Promise returned to indicate that the PreviewOutput instance is removed.'); }) @@ -1607,7 +1609,7 @@ Removes a **PhotoOutput** instance from this **CaptureSession** instance. This A **Example** -``` +```js captureSession.removeOutput(photoOutput, (err) => { if (err) { console.error('Failed to remove the PhotoOutput instance. ${err.message}'); @@ -1641,7 +1643,7 @@ Removes a **PhotoOutput** instance from this **CaptureSession** instance. This A **Example** -``` +```js captureSession.removeOutput(photoOutput).then(() => { console.log('Promise returned to indicate that the PhotoOutput instance is removed.'); }) @@ -1664,7 +1666,7 @@ Removes a **VideoOutput** instance from this **CaptureSession** instance. This A **Example** -``` +```js captureSession.removeOutput(videoOutput, (err) => { if (err) { console.error('Failed to remove the VideoOutput instance. ${err.message}'); @@ -1698,7 +1700,7 @@ Removes a **VideoOutput** instance from this **CaptureSession** instance. This A **Example** -``` +```js captureSession.removeOutput(videoOutput).then(() => { console.log('Promise returned to indicate that the VideoOutput instance is removed.'); }) @@ -1720,7 +1722,7 @@ Starts this **CaptureSession** instance. This API uses an asynchronous callback **Example** -``` +```js captureSession.start((err) => { if (err) { console.error('Failed to start the session ${err.message}'); @@ -1746,7 +1748,7 @@ Starts this **CaptureSession** instance. This API uses a promise to return the r **Example** -``` +```js captureSession.start().then(() => { console.log('Promise returned to indicate the session start success.'); }) @@ -1769,7 +1771,7 @@ Stops this **CaptureSession** instance. This API uses an asynchronous callback t **Example** -``` +```js captureSession.stop((err) => { if (err) { console.error('Failed to stop the session ${err.message}'); @@ -1795,7 +1797,7 @@ Stops this **CaptureSession** instance. This API uses a promise to return the re **Example** -``` +```js captureSession.stop().then(() => { console.log('Promise returned to indicate the session stop success.'); }) @@ -1817,7 +1819,7 @@ Releases this **CaptureSession** instance. This API uses an asynchronous callbac **Example** -``` +```js captureSession.release((err) => { if (err) { console.error('Failed to release the CaptureSession instance ${err.message}'); @@ -1843,7 +1845,7 @@ Releases this **CaptureSession** instance. This API uses a promise to return the **Example** -``` +```js captureSession.release().then(() => { console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); }) @@ -1859,40 +1861,38 @@ Listens for **CaptureSession** errors. This API uses a callback to return the er **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :---------------------------------- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the capture session error event.| -| callback | ErrorCallback | Yes | Callback used to return the capture session errors. | +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------------------- | :--- | :-------------------------------------------- | +| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the capture session error event.| +| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. | **Example** -``` +```js captureSession.on('error', (captureSessionError) => { console.log('Capture session error code: ' + captureSessionError.code); }) ``` -## CaptureSessionErrorCode +## CaptureSessionErrorCode -Enumerates the CaptureSession error code. +Enumerates the **CaptureSession** error codes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| ERROR_UNKNOWN | -1 | Unknown error.| +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -## CaptureSessionError +## CaptureSessionError -Capture session error object which extends **Error** interface. +Defines a **CaptureSession** error object. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| code | [CaptureSessionErrorCode](#capturesessionerrorcode) | Used to get error code in CaptureSession on('error') callback.| +| Name| Type | Description | +| ---- | ------------------------------------------- | -------------------------- | +| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| ## camera.createPreviewOutput @@ -1911,7 +1911,7 @@ Creates a **PreviewOutput** instance. This API uses an asynchronous callback to **Example** -``` +```js camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { if (err) { console.error('Failed to create the PreviewOutput instance. ${err.message}'); @@ -1943,7 +1943,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the inst **Example** -``` +```js camera.createPreviewOutput("surfaceId").then((previewOutput) => { console.log('Promise returned with the PreviewOutput instance'); }) @@ -1969,7 +1969,7 @@ Releases this **PreviewOutput** instance. This API uses an asynchronous callback **Example** -``` +```js previewOutput.release((err) => { if (err) { console.error('Failed to release the PreviewOutput instance ${err.message}'); @@ -1996,7 +1996,7 @@ Releases this **PreviewOutput** instance. This API uses a promise to return the **Example** -``` +```js previewOutput.release().then(() => { console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); }) @@ -2019,7 +2019,7 @@ Listens for preview frame start events. This API uses an asynchronous callback t **Example** -``` +```js previewOutput.on('frameStart', () => { console.log('Preview frame started'); }) @@ -2042,7 +2042,7 @@ Listens for preview frame end events. This API uses an asynchronous callback to **Example** -``` +```js previewOutput.on('frameEnd', () => { console.log('Preview frame ended'); }) @@ -2058,14 +2058,14 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the preview output error event.| -| callback | ErrorCallback | Yes | Callback used to return the preview output errors. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------------------------------------------- | :--- | :-------------------------------------------- | +| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the preview output error event.| +| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. | **Example** -``` +```js previewOutput.on('error', (previewOutputError) => { console.log('Preview output error code: ' + previewOutputError.code); }) @@ -2073,25 +2073,23 @@ previewOutput.on('error', (previewOutputError) => { ## PreviewOutputErrorCode -Enumerates the PreviewOutput error code. +Enumerates the **PreviewOutput** error codes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| ERROR_UNKNOWN | -1 | Unknown error.| +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -## PreviewOutputError +## PreviewOutputError -Preview output error object which extends **Error** interface. +Defines a **PreviewOutput** error object. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | Used to get error code in PreviewOutput on('error') callback.| +| Name| Type | Description | +| ---- | ------------------------------------------------- | ---------------------- | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| ## camera.createPhotoOutput @@ -2110,7 +2108,7 @@ Creates a **PhotoOutput** instance. This API uses an asynchronous callback to re **Example** -``` +```js camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { if (err) { console.error('Failed to create the PhotoOutput instance. ${err.message}'); @@ -2142,7 +2140,7 @@ Creates a **PhotoOutput** instance. This API uses a promise to return the instan **Example** -``` +```js camera.createPhotoOutput("surfaceId").then((photoOutput) => { console.log('Promise returned with PhotoOutput instance'); }) @@ -2153,14 +2151,12 @@ Enumerates the image rotation angles. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ------------ | ------ | --------------- | -| ROTATION_0 | 0 | The image rotates 0 degrees. | -| ROTATION_90 | 90 | The image rotates 90 degrees. | -| ROTATION_180 | 180 | The image rotates 180 degrees.| -| ROTATION_270 | 270 | The image rotates 270 degrees.| - - +| Name | Value | Description | +| ------------ | ---- | --------------- | +| ROTATION_0 | 0 | The image rotates 0 degrees. | +| ROTATION_90 | 90 | The image rotates 90 degrees. | +| ROTATION_180 | 180 | The image rotates 180 degrees.| +| ROTATION_270 | 270 | The image rotates 270 degrees.| ## QualityLevel @@ -2168,23 +2164,23 @@ Enumerates the image quality levels. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| -------------------- | ------ | -------------- | -| QUALITY_LEVEL_HIGH | 0 | High image quality. | -| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| -| QUALITY_LEVEL_LOW | 2 | Low image quality. | +| Name | Value | Description | +| -------------------- | ---- | -------------- | +| QUALITY_LEVEL_HIGH | 0 | High image quality. | +| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| +| QUALITY_LEVEL_LOW | 2 | Low image quality. | ## PhotoCaptureSetting -Defines the settings for image capture. +Defines the settings for photo capture. **System capability**: SystemCapability.Multimedia.Camera.Core | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | -------------- | -| quality | [QualityLevel](#qualitylevel) | No | Photo image quality. | -| rotation | [ImageRotation](#imagerotation) | No | Photo rotation.| +| quality | [QualityLevel](#qualitylevel) | No | Photo quality. | +| rotation | [ImageRotation](#imagerotation) | No | Rotation angle of the photo.| ## PhotoOutput @@ -2207,7 +2203,7 @@ Captures a photo. This API uses an asynchronous callback to return the result. **Example** -``` +```js photoOutput.capture((err) => { if (err) { console.error('Failed to capture the photo ${err.message}'); @@ -2234,7 +2230,7 @@ Captures a photo with the specified capture settings. This API uses an asynchron **Example** -``` +```js photoOutput.capture(settings, (err) => { if (err) { console.error('Failed to capture the photo ${err.message}'); @@ -2267,7 +2263,7 @@ Captures a photo with the specified capture settings. This API uses a promise to **Example** -``` +```js photoOutput.capture().then(() => { console.log('Promise returned to indicate that photo capture request success.'); }) @@ -2289,7 +2285,7 @@ Releases this **PhotoOutput** instance. This API uses an asynchronous callback t **Example** -``` +```js photoOutput.release((err) => { if (err) { console.error('Failed to release the PhotoOutput instance ${err.message}'); @@ -2316,7 +2312,7 @@ Releases this **PhotoOutput** instance. This API uses a promise to return the re **Example** -``` +```js photoOutput.release().then(() => { console.log('Promise returned to indicate that the PhotoOutput instance is released successfully.'); }) @@ -2326,7 +2322,7 @@ photoOutput.release().then(() => { on(type: 'captureStart', callback: AsyncCallback): void -Listens for photo capture start events. This API uses a callback to return the event information. +Listens for photo capture start events. This API uses an asynchronous callback to return the capture ID. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2339,7 +2335,7 @@ Listens for photo capture start events. This API uses a callback to return the e **Example** -``` +```js photoOutput.on('captureStart', (err, captureId) => { console.log('photo capture stated, captureId : ' + captureId); }) @@ -2349,20 +2345,20 @@ photoOutput.on('captureStart', (err, captureId) => { on(type: 'frameShutter', callback: AsyncCallback): void -Listens for frame shutter events. This API uses a callback to return the event information. +Listens for frame shutter events. This API uses an asynchronous callback to return the event information. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------------- | :--- | :--------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **frameShutter**, indicating the frame shutter event.| -| callback | AsyncCallback | Yes | Callback used to return the frame shutter information. | +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------- | +| type | string | Yes | Type of event to listen for. The value is fixed at **frameShutter**, indicating the frame shutter event.| +| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the information. | **Example** -``` +```js photoOutput.on('frameShutter', (frameShutterInfo) => { console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); @@ -2373,20 +2369,20 @@ photoOutput.on('frameShutter', (frameShutterInfo) => { on(type: 'captureEnd', callback: AsyncCallback): void -Listens for photo capture end events. This API uses a callback to return the event information. +Listens for photo capture end events. This API uses an asynchronous callback to return the event information. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------------- | :--- | :--------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **captureEnd**, indicating the photo capture end event.| -| callback | AsyncCallback | Yes | Callback used to return the photo capture end information. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------------------------------ | :--- | :--------------------------------------------- | +| type | string | Yes | Type of event to listen for. The value is fixed at **captureEnd**, indicating the photo capture end event.| +| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the information. | **Example** -``` +```js photoOutput.on('captureEnd', (captureEndInfo) => { console.log('photo capture end, captureId : ' + captureEndInfo.captureId); console.log('frameCount : ' + captureEndInfo.frameCount); @@ -2403,62 +2399,60 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------------- | :--- | :---------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the photo output error event.| -| callback | ErrorCallback | Yes | Callback used to return the photo output errors. | +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------------- | :--- | :---------------------------------------- | +| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the photo output error event.| +| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. | **Example** -``` +```js photoOutput.on('error', (photoOutputError) => { console.log('Photo output error code: ' + photoOutputError.code); }) ``` -### FrameShutterInfo +## FrameShutterInfo -Frame shutter callback info which provides **captureId** & **timestamp** parameteres & indicates the frame shutter event. +Defines the frame shutter information. -**Parameteres** +**System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| :------- | :------------------------------- | :--- | :---------------------------------------- | -| captureId | number | Yes | Capture id.| -| timestamp | number | Yes | Timestamp for frame. +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ----------------------------- | +| captureId | number | Yes | ID of this capture action.| +| timestamp | number | Yes | Timestamp when the frame shutter event is triggered. | -### CaptureEndInfo +## CaptureEndInfo -Capture end info which provides **captureId** & **frameCount** parameteres & indicates the photo capture end event. +Defines the capture end information. -**Parameteres** +**System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| :------- | :------------------------------- | :--- | :---------------------------------------- | -| captureId | number | Yes | Capture id.| -| frameCount | number | Yes | Frame count. +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ----------------------------- | +| captureId | number | Yes | ID of this capture action.| +| frameCount | number | Yes | Number of frames captured. | ## PhotoOutputErrorCode -Enumerates the PhotoOutput error code. +Enumerates the **PhotoOutput** error codes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| ERROR_UNKNOWN | -1 | Unknown error.| +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -## PhotoOutputError +## PhotoOutputError -Photo output error object which extends **Error** interface. +Defines a **PhotoOutput** error object. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Used to get error code in PhotoOutput on('error') callback.| +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | **PhotoOutput** error code.| ## camera.createVideoOutput @@ -2477,7 +2471,7 @@ Creates a **VideoOutput** instance. This API uses an asynchronous callback to re **Example** -``` +```js camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { if (err) { console.error('Failed to create the VideoOutput instance. ${err.message}'); @@ -2509,7 +2503,7 @@ Creates a **VideoOutput** instance. This API uses a promise to return the instan **Example** -``` +```js camera.createVideoOutput("surfaceId" ).then((videoOutput) => { console.log('Promise returned with the VideoOutput instance'); @@ -2536,7 +2530,7 @@ Starts the video output. This API uses an asynchronous callback to return the re **Example** -``` +```js videoOutput.start((err) => { if (err) { console.error('Failed to start the video output ${err.message}'); @@ -2563,7 +2557,7 @@ Starts the video output. This API uses a promise to return the result. **Example** -``` +```js videoOutput.start().then(() => { console.log('Promise returned to indicate that start method execution success.'); }) @@ -2585,7 +2579,7 @@ Stops the video output. This API uses an asynchronous callback to return the res **Example** -``` +```js videoOutput.stop((err) => { if (err) { console.error('Failed to stop the video output ${err.message}'); @@ -2611,7 +2605,7 @@ Stops the video output. This API uses a promise to return the result. **Example** -``` +```js videoOutput.start().then(() => { console.log('Promise returned to indicate that stop method execution success.'); }) @@ -2633,7 +2627,7 @@ Releases this **VideoOutput** instance. This API uses an asynchronous callback t **Example** -``` +```js videoOutput.release((err) => { if (err) { console.error('Failed to release the VideoOutput instance ${err.message}'); @@ -2660,7 +2654,7 @@ Releases this **VideoOutput** instance. This API uses a promise to return the re **Example** -``` +```js videoOutput.release().then(() => { console.log('Promise returned to indicate that the VideoOutput instance is released successfully.'); }) @@ -2670,7 +2664,7 @@ videoOutput.release().then(() => { on(type: 'frameStart', callback: AsyncCallback): void -Listens for video frame start events. This API uses a callback to return the event information. +Listens for video frame start events. This API uses an asynchronous callback to return the event information. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2683,7 +2677,7 @@ Listens for video frame start events. This API uses a callback to return the eve **Example** -``` +```js videoOutput.on('frameStart', () => { console.log('Video frame started'); }) @@ -2693,7 +2687,7 @@ videoOutput.on('frameStart', () => { on(type: 'frameEnd', callback: AsyncCallback): void -Listens for video frame end events. This API uses a callback to return the event information. +Listens for video frame end events. This API uses an asynchronous callback to return the event information. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2706,7 +2700,7 @@ Listens for video frame end events. This API uses a callback to return the event **Example** -``` +```js videoOutput.on('frameEnd', () => { console.log('Video frame ended'); }) @@ -2722,14 +2716,14 @@ Listens for **VideoOutput** errors. This API uses a callback to return the error **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :-------------------------- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the video output error event.| -| callback | Callback | Yes | Callback used to return the video output errors. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------------------------------- | :--- | :-------------------------------------------- | +| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the video output error event.| +| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | **Example** -``` +```js videoOutput.on('error', (VideoOutputError) => { console.log('Video output error code: ' + VideoOutputError.code); }) @@ -2737,22 +2731,20 @@ videoOutput.on('error', (VideoOutputError) => { ## VideoOutputErrorCode -Enumerates the VideoOutput error code. +Enumerates the **VideoOutput** error codes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| ERROR_UNKNOWN | -1 | Unknown error.| +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -## VideoOutputError +## VideoOutputError -Photo output error object which extends **Error** interface. +Defines a **VideoOutput** error object. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Default Value| Description | -| ---------------------- | ------ | ------------ | -| code | [VideoOutputErrorCode](#videooutputerrorcode) | Used to get error code in VideoOutput on('error') callback.| \ No newline at end of file +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | **VideoOutput** error code.| diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 3f0d063a7e435b2f777f79bb6934aaf8d233e13a..7c65ecbd616c0bd3ea8fb0c7f7b12a06b67533d4 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,12 +1,12 @@ # Standard NFC Card Emulation -Implements Near-Field Communication (NFC) card emulation. +The cardEmulation module implements Near-Field Communication (NFC) card emulation. > **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** +## Modules to Import ``` import cardEmulation from '@ohos.nfc.cardEmulation'; 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 b801f7038e84713dd3096a7c7c63f3a03314e2a5..a1c0aba0f59aa5831cfa2e54cbad92302b8724c8 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,6 +1,8 @@ # DataAbilityPredicates -> **NOTE** +**DataAbility** provides APIs for creating predicates, which implement different query methods for relational database (RDB) stores. + +> **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. @@ -24,15 +26,15 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Table name in the RDB store.| -| 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** ```js @@ -58,15 +60,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -85,15 +87,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -112,9 +114,9 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** ```js @@ -138,9 +140,9 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** ```js @@ -164,9 +166,9 @@ Adds the OR condition to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** ```js @@ -187,9 +189,9 @@ Adds the AND condition to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** ```js @@ -210,15 +212,15 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -237,15 +239,15 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -264,15 +266,15 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ``` @@ -291,14 +293,14 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -317,14 +319,14 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -343,15 +345,15 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -370,15 +372,15 @@ Sets a **DataAbilityPredicates** object to match the specified string. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -392,21 +394,21 @@ Sets a **DataAbilityPredicates** object to match the specified string. between(field: string, low: ValueType, high: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value within the specified range. +Sets a **DataAbilityPredicates** object to match a field whose data type is **ValueType** and value is within the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -425,16 +427,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -453,15 +455,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -480,15 +482,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -507,15 +509,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -534,15 +536,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -561,14 +563,14 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -587,14 +589,14 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -613,9 +615,9 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -634,14 +636,14 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -660,14 +662,14 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -686,14 +688,14 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -705,20 +707,20 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i indexedBy(field: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to specify the index column. -**System capability**: SystemCapability.DistributedDataManager.DataShare.Core +Sets a **DataAbilityPredicates** object to specify the index column. +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -737,16 +739,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js @@ -765,16 +767,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **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** ```js 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 a58a4583a1db69548342f0c63b8a13aec0dfb623..83875a6edb8aa2395b8750e70fb86b7fa596b03d 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,6 +1,6 @@ # Distributed Data Object -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. +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. > **NOTE**
> @@ -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| @@ -33,12 +33,11 @@ Creates a distributed data object. | [DistributedObject](#distributedobject) | Distributed data object created.| **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject'; - // Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, - parent:{mother:"jack mom",father:"jack Dad"}}); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +``` ## distributedObject.genSessionId @@ -50,15 +49,15 @@ 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 - import distributedObject from '@ohos.data.distributedDataObject'; - var sessionId = distributedObject.genSessionId(); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var sessionId = distributedObject.genSessionId(); +``` ## SaveSuccessResponse9+ @@ -98,27 +97,26 @@ 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** - ```js - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, - parent:{mother:"jack mom",father:"jack Dad"}}); - // Add g_object to the distributed network. - g_object.setSessionId(distributedObject.genSessionId()); - // Remove g_object from the distributed network. - g_object.setSessionId(""); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId()); +// Remove g_object from the distributed network. +g_object.setSessionId(""); +``` ### on('change') @@ -130,15 +128,15 @@ 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 import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.changeCallback = (sessionId, changeData) => { console.info("change" + sessionId); if (changeData != null && changeData != undefined) { @@ -159,16 +157,16 @@ 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** ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // Unregister the specified data change callback. g_object.off("change", globalThis.changeCallback); // Unregister all data change callbacks. @@ -184,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 @@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject'; globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); g_object.on("status", globalThis.statusCallback); ``` @@ -209,16 +207,16 @@ 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** ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } @@ -245,24 +243,24 @@ 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](#savesuccessresponse)> | 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** - - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.save("local", (result)=>{ - console.log("save callback"); - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local", (status, result)=>{ + console.log("save status = " + status); + console.log("save callback"); + console.info("save sessionId: " + result.sessionId); + console.info("save version: " + result.version); + console.info("save deviceId: " + result.deviceId); +}); +``` ### save9+ @@ -281,31 +279,31 @@ 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** +**Return value** -| Type| Description| -| -------- | -------- | -| Promise<[SaveSuccessResponse](#savesuccessresponse)> | 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** - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.save("local").then((result)=>{ - console.log("save callback"); - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); - }, ()=>{ - console.error("save failed"); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local").then((result)=>{ + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, ()=>{ + console.error("save failed"); +}); +``` ### revokeSave9+ @@ -319,20 +317,20 @@ 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](#revokesavesuccessresponse)> | 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** - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.revokeSave((result, data) =>{ - console.log("revokeSave callback"); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.revokeSave((result, data) =>{ + console.log("revokeSave callback"); +}); +``` ### revokeSave9+ @@ -345,22 +343,22 @@ If the object is stored on another device, the data on the local device will be **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject - **Return value** +**Return value** -| Type| Description| -| -------- | -------- | -| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse)> | 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** - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.revokeSave("local").then((result)=>{ - console.log("revokeSave callback"); - console.log("sessionId" + result.sessionId); - }, ()=>{ - console.error("revokeSave failed"); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.revokeSave().then((result)=>{ + console.log("revokeSave callback"); + console.log("sessionId" + result.sessionId); +}, ()=>{ + console.error("revokeSave failed"); +}); +``` 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 73d27f9f20009d0674b4cf07e017139988d09fbe..63371ed42b8eb940caa8072ffda6aa17d78658c5 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,6 +1,6 @@ # Preferences -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. +Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, the keys are of the string type, and the values can be of the number, string, Boolean, Array\, Array\, or Array\ type. > **NOTE**
@@ -33,11 +33,11 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| -| name | string | Yes| Name of the **Preferences** instance persistence file.| -| callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| + | name | string | Yes| Name of the **Preferences** instance persistence file.| + | callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| **Example** ```ts @@ -60,15 +60,15 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| -| name | string | Yes| Name of the **Preferences** instance persistence file.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| + | name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[Preferences](#preferences)> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<[Preferences](#preferences)> | Promise used to return the result.| **Example** ```ts @@ -91,11 +91,11 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| -| name | string | Yes| Name of the **Preferences** instance persistence file.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| + | name | string | Yes| Name of the **Preferences** instance persistence file.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts @@ -119,15 +119,15 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| -| name | string | Yes| Name of the **Preferences** instance persistence file.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| + | name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| **Example** ```ts @@ -151,11 +151,11 @@ When a **Preferences** singleton instance is removed, this instance cannot be us **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| -| name | string | Yes| Name of the **Preferences** instance persistence file.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| + | name | string | Yes| Name of the **Preferences** instance persistence file.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts @@ -180,15 +180,15 @@ When a **Preferences** singleton instance is removed, this instance cannot be us **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| -| name | string | Yes| Name of the **Preferences** instance persistence file.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| + | name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| **Example** ```ts @@ -218,7 +218,7 @@ Obtains the value of a key. If the value is null or a non-default value, the def | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the data to obtain. It cannot be empty.| -| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array. | callback | AsyncCallback<ValueType> | Yes| Callback used to return the result.| **Example** @@ -241,16 +241,16 @@ Obtains the value of a key. If the value is null or a non-default value, the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -**Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to obtain. It cannot be empty.| -| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | key | string | Yes| Key of the data to obtain. It cannot be empty.| + | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<ValueType> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<ValueType> | Promise used to return the result.| **Example** ```ts @@ -271,13 +271,13 @@ Obtains the **Object** instance that contains all KV pairs. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Object> | Yes| Callback used to return the **Object** instance obtained.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<Object> | Yes| Callback used to return the **Object** instance obtained.| **Example** ```ts -preferences.get.getAll(function (err, value) { +preferences.getAll(function (err, value) { if (err) { console.info("getAll failed, err: " + err) return @@ -298,9 +298,9 @@ Obtains the **Object** instance that contains all KV pairs. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** -| Type| Description| -| -------- | -------- | -| Promise<Object> | Promise used to return the **Object** instance obtained.| + | Type| Description| + | -------- | -------- | + | Promise<Object> | Promise used to return the **Object** instance obtained.| **Example** ```ts @@ -323,11 +323,11 @@ Puts a new value to this **Preferences** instance and its persistence file. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data. It cannot be empty.| -| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | key | string | Yes| Key of the data. It cannot be empty.| + | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts @@ -350,15 +350,15 @@ Puts a new value to this **Preferences** instance and its persistence file. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data. It cannot be empty.| -| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | key | string | Yes| Key of the data. It cannot be empty.| + | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| **Example** ```ts @@ -380,10 +380,10 @@ Checks whether this **Preferences** instance contains data with a given key. Thi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to check. It cannot be empty.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | key | string | Yes| Key of the data to check. It cannot be empty.| + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| **Example** ```ts @@ -410,14 +410,14 @@ Checks whether this **Preferences** instance contains data with a given key. Thi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to check. It cannot be empty.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | key | string | Yes| Key of the data to check. It cannot be empty.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| **Example** ```ts @@ -443,10 +443,10 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the KV pair to delete. It cannot be empty.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts @@ -469,14 +469,14 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the KV pair to delete. It cannot be empty.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| **Example** ```ts @@ -498,9 +498,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts @@ -523,9 +523,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| **Example** ```ts @@ -547,9 +547,9 @@ Clears data of this **Preferences** instance. This API uses an asynchronous call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts @@ -572,9 +572,9 @@ Clears data of this **Preferences** instance. This API uses a promise to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| **Example** ```ts @@ -596,33 +596,36 @@ Subscribes to data changes. When the value of the subscribed key changes, a call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value **change** indicates data change events.| -| callback | Callback<{ key : string }> | Yes| Callback used to return data changes.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **change** indicates data change events.| + | callback | Callback<{ key : string }> | Yes| Callback used to return data changes.| **Example** ```ts -var observer = function (key) { - console.info("The key of " + key + " changed.") -} - -... - -preferences.on('change', observer) -preferences.put('startup', 'auto', function (err) { +data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to get preferences.") + return; } - console.info("Put the value of startup successfully.") - - preferences.flush(function (err) { + var observer = function (key) { + console.info("The key of " + key + " changed.") + } + preferences.on('change', observer) + preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) + console.info("Failed to put the value of startup, err: " + err) return } - console.info("Flushed data to file successfully.") // The observer will be called. + console.info("Put the value of startup successfully.") + + preferences.flush(function (err) { + if (err) { + console.info("Failed to flush data to file, err: " + err) + return + } + console.info("Flushed data to file successfully.") // The observer will be called. + }) }) }) ``` @@ -637,33 +640,36 @@ Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value **change** indicates data change events.| -| callback | Callback<{ key : string }> | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **change** indicates data change events.| + | callback | Callback<{ key : string }> | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.| **Example** ```ts -var observer = function (key) { - console.info("The key of " + key + " changed.") -} - -... - -preferences.on('change', observer) -preferences.put('startup', 'auto', function (err) { +data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to get preferences.") + return; } - console.info("Put the value of startup successfully.") - - preferences.flush(function (err) { + var observer = function (key) { + console.info("The key of " + key + " changed.") + } + preferences.on('change', observer) + preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) + console.info("Failed to put the value of startup, err: " + err) return } - console.info("Flushed data to file successfully.") // The observer will be called. + console.info("Put the value of startup successfully.") + + preferences.flush(function (err) { + if (err) { + console.info("Failed to flush data to file, err: " + err) + return + } + console.info("Flushed data to file successfully.") // The observer will be called. + }) preferences.off('change', observer) }) }) @@ -675,8 +681,11 @@ Enumerates the value types. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name | Description | -| ------- | -------------------- | -| number | The value is a number. | -| string | The value is a string. | -| boolean | The value is of Boolean type.| +| Name | Description | +| -------------- | ------------------------------ | +| number | The value is a number. | +| string | The value is a string. | +| boolean | The value is of Boolean type. | +| Array\ | The value is an array of numbers. | +| Array\ | The value is a Boolean array. | +| Array\ | The value is an array of the strings.| 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 ac26222e5da8c26216901b3de93bec9b4f22133b..71b5d2bec230d88f378b1fa122319e8ba983c6e7 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -29,7 +29,7 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context | Context | Yes| Context of the application or functionality.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| +| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | version | number | Yes| RDB store version.| | callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| @@ -59,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context | Context | Yes| Context of the application or functionality.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| +| context | Context | Yes|Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | version | number | Yes| RDB store version.| @@ -92,7 +92,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context | Context | Yes| Context of the application or functionality.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| +| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | name | string | Yes| Name of the RDB store to delete.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| @@ -118,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context | Context | Yes| Context of the application or functionality.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| +| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | name | string | Yes| Name of the RDB store to delete.| **Return value** @@ -1018,7 +1018,7 @@ const valueBucket = { } let promise = rdbStore.insert("EMPLOYEE", valueBucket) promise.then(async (ret) => { - console.log("Insert first done: " + ret) + console.log("Inserted first row: " + ret) }).catch((err) => { console.log("Failed to insert data, err: " + err) }) @@ -1029,16 +1029,16 @@ promise.then(async (ret) => { update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void -Updates data in the database based on the specified RdbPredicates object. This API uses an asynchronous callback to return the result. +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| -| callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** ```js @@ -1064,14 +1064,14 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> -Updates data in the database based on the specified RdbPredicates object. This API uses a promise to return the result. +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| **Return value** @@ -1100,7 +1100,7 @@ promise.then(async (ret) => { ### update9+ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void -Updates data in the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. +Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1108,9 +1108,9 @@ Updates data in the database based on the specified **DataSharePredicates** obje | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| -| callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** ```js @@ -1135,7 +1135,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise<number> -Updates data in the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. +Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1143,7 +1143,7 @@ Updates data in the database based on the specified **DataSharePredicates** obje | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| **Return value** @@ -1175,7 +1175,7 @@ promise.then(async (ret) => { delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void -Deletes data from the database based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1203,7 +1203,7 @@ rdbStore.delete(predicates, function (err, rows) { delete(predicates: RdbPredicates):Promise<number> -Deletes data from the database based on the specified **RdbPredicates** object. This API uses a promise to return the result. +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1215,7 +1215,7 @@ Deletes data from the database based on the specified **RdbPredicates** object. **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| +| Promise<number> | Promise used to return the number of rows updated.| **Example** ```js @@ -1234,7 +1234,7 @@ promise.then((rows) => { delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback<number>):void -Deletes data from the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1262,7 +1262,7 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> -Deletes data from the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1275,7 +1275,7 @@ Deletes data from the database based on the specified **DataSharePredicates** ob **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| +| Promise<number> | Promise used to return the number of rows updated.| **Example** ```js @@ -1294,7 +1294,7 @@ promise.then((rows) => { query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. +Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1324,7 +1324,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> -Queries data in the database based on specified conditions. This API uses a promise to return the result. +Queries data in the RDB store based on specified conditions. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1356,7 +1356,7 @@ Queries data in the database based on specified conditions. This API uses a prom query(predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. +Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1386,7 +1386,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], query(predicates: DataSharePredicates, columns?: Array<string>):Promise<ResultSet> -Queries data in the database based on specified conditions. This API uses a promise to return the result. +Queries data in the RDB store based on specified conditions. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1625,14 +1625,14 @@ try { backup(destName:string, callback: AsyncCallback<void>):void -Backs up the database with the specified name. This API uses an asynchronous callback to return the result. +Backs up an RDB store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the database backup file.| +| destName | string | Yes| Name of the RDB store backup file.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** @@ -1650,14 +1650,14 @@ rdbStore.backup("dbBackup.db", function(err) { backup(destName:string): Promise<void> -Backs up the database with the specified name. This API uses a promise to return the result. +Backs up an RDB store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the database backup file.| +| destName | string | Yes| Name of the RDB store backup file.| **Return value** | Type| Description| @@ -1678,14 +1678,14 @@ promiseBackup.then(()=>{ restore(srcName:string, callback: AsyncCallback<void>):void -Restores a database from a specified database backup file. This API uses an asynchronous callback to return the result. +Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the database backup file.| +| srcName | string | Yes| Name of the RDB store backup file.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** @@ -1703,14 +1703,14 @@ rdbStore.restore("dbBackup.db", function(err) { restore(srcName:string): Promise<void> -Restores a database from a specified database backup file. This API uses a promise to return the result. +Restores an RDB store using a backup file. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the database backup file.| +| srcName | string | Yes| Name of the RDB store backup file.| **Return value** | Type| Description| @@ -1809,7 +1809,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, console.info('Failed to obtain DistributedTableName, err: ' + err) return } - console.info('Obtained DistributedTableName successfully, tableName=.' + tableName) + console.info('Obtained distributed table name successfully, tableName=.' + tableName) }) ``` @@ -1839,7 +1839,7 @@ Obtains the distributed table name for a remote device based on the local table ```js let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") promise.then((tableName) => { - console.info('Obtained DistributedTableName successfully, tableName= ' + tableName) + console.info('Obtained distributed table name successfully, tableName= ' + tableName) }).catch((err) => { console.info('Failed to obtain DistributedTableName, err: ' + err) }) 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 613e793255ded14a1ae050bdf4504e402b52b941..3098499d48ca52b0251cfb9648cc032fc26e2652 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,12 +1,15 @@ # Result Set +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**
+> > 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. ## Usage -You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain the **resultSet** object. +You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain a **resultSet** object. ```js import dataRdb from '@ohos.data.rdb'; @@ -20,7 +23,7 @@ promise.then((resultSet) => { ## ResultSet -Provides methods to access the result set, which is obtained by querying the relational database (RDB) store. +Provides methods to access the result set, which is obtained by querying the RDB store. ### Attributes diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md index 6cdfcf94fdf36dd3f9d4adb4e44420394120fd10..47a961f7cceb3c20de583387d9ed54d5494e5ac4 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -13,7 +13,7 @@ Lightweight storage provides applications with data processing capability and al ## Modules to Import ```js -import dataStorage from '@ohos.data.storage'; +import data_storage from '@ohos.data.storage'; ``` ## Constants @@ -26,7 +26,7 @@ import dataStorage from '@ohos.data.storage'; | MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| -## dataStorage.getStorageSync +## data_storage.getStorageSync getStorageSync(path: string): Storage @@ -46,24 +46,17 @@ Reads the specified file and loads its data to the **Storage** instance for data **Example** ```js - import dataStorage from '@ohos.data.storage' - import featureAbility from '@ohos.ability.featureAbility' + import data_storage from '@ohos.data.storage' + + let path = '/data/storage/el2/database' + let storage = data_storage.getStorageSync(path + '/mystore') + storage.putSync('startup', 'auto') + storage.flushSync() - var context = featureAbility.getContext() - context.getFilesDir((err, path) => { - if (err) { - console.error('getFilesDir failed. err: ' + JSON.stringify(err)); - return; - } - console.info('getFilesDir successful. path:' + JSON.stringify(path)); - let storage = dataStorage.getStorageSync(path + '/mystore') - storage.putSync('startup', 'auto') - storage.flushSync() - }); ``` -## dataStorage.getStorage +## data_storage.getStorage getStorage(path: string, callback: AsyncCallback<Storage>): void @@ -79,29 +72,21 @@ Reads the specified file and loads its data to the **Storage** instance for data **Example** ```js - import dataStorage from '@ohos.data.storage' - import featureAbility from '@ohos.ability.featureAbility' + import data_storage from '@ohos.data.storage' - var context = featureAbility.getContext() - context.getFilesDir((err, path) => { + let path = '/data/storage/el2/database' + data_storage.getStorage(path + '/mystore', function (err, storage) { if (err) { - console.error('getFilesDir failed. err: ' + JSON.stringify(err)); + console.info("Failed to get the storage. Path: " + path + '/mystore') return; } - console.info('getFilesDir successful. path:' + JSON.stringify(path)); - dataStorage.getStorage(path + '/mystore', function (err, storage) { - if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') - return; - } - storage.putSync('startup', 'auto') - storage.flushSync() - }) - }); + storage.putSync('startup', 'auto') + storage.flushSync() + }) ``` -## dataStorage.getStorage +## data_storage.getStorage getStorage(path: string): Promise<Storage> @@ -121,28 +106,21 @@ Reads the specified file and loads its data to the **Storage** instance for data **Example** ```js - import dataStorage from '@ohos.data.storage' - import featureAbility from '@ohos.ability.featureAbility' + import data_storage from '@ohos.data.storage' - var context = featureAbility.getContext() - context.getFilesDir((err, path) => { - if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') - return; - } - console.info('getFilesDir successful. path:' + JSON.stringify(path)); - let promisegetSt = dataStorage.getStorage(path + '/mystore') - promisegetSt.then((storage) => { - storage.putSync('startup', 'auto') - storage.flushSync() - }).catch((err) => { - console.info("Get the storage failed, path: " + path + '/mystore') - }) - }); + let path = '/data/storage/el2/database' + + let getPromise = data_storage.getStorage(path + '/mystore') + getPromise.then((storage) => { + storage.putSync('startup', 'auto') + storage.flushSync() + }).catch((err) => { + console.info("Failed to get the storage. Path: " + path + '/mystore') + }) ``` -## dataStorage.deleteStorageSync +## data_storage.deleteStorageSync deleteStorageSync(path: string): void @@ -157,11 +135,12 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Example** ```js - dataStorage.deleteStorageSync(path + '/mystore') + let path = '/data/storage/el2/database' + data_storage.deleteStorageSync(path + '/mystore') ``` -## dataStorage.deleteStorage +## data_storage.deleteStorage deleteStorage(path: string, callback: AsyncCallback<void>): void @@ -173,11 +152,12 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```js - dataStorage.deleteStorage(path + '/mystore', function (err) { + let path = '/data/storage/el2/database' + data_storage.deleteStorage(path + '/mystore', function (err) { if (err) { console.info("Deleted failed with err: " + err) return @@ -187,7 +167,7 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete ``` -## dataStorage.deleteStorage +## data_storage.deleteStorage deleteStorage(path: string): Promise<void> @@ -203,11 +183,12 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js - let promisedelSt = dataStorage.deleteStorage(path + '/mystore') + let path = '/data/storage/el2/database' + let promisedelSt = data_storage.deleteStorage(path + '/mystore') promisedelSt.then(() => { console.info("Deleted successfully.") }).catch((err) => { @@ -216,7 +197,7 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete ``` -## dataStorage.removeStorageFromCacheSync +## data_storage.removeStorageFromCacheSync removeStorageFromCacheSync(path: string): void @@ -231,11 +212,12 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **Example** ```js - dataStorage.removeStorageFromCacheSync(path + '/mystore') + let path = '/data/storage/el2/database' + data_storage.removeStorageFromCacheSync(path + '/mystore') ``` -## dataStorage.removeStorageFromCache +## data_storage.removeStorageFromCache removeStorageFromCache(path: string, callback: AsyncCallback<void>): void @@ -247,11 +229,12 @@ Removes the singleton **Storage** instance of a file from the cache. The removed | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```js - dataStorage.removeStorageFromCache(path + '/mystore', function (err) { + let path = '/data/storage/el2/database' + data_storage.removeStorageFromCache(path + '/mystore', function (err) { if (err) { console.info("Removed storage from cache failed with err: " + err) return @@ -261,7 +244,7 @@ Removes the singleton **Storage** instance of a file from the cache. The removed ``` -## dataStorage.removeStorageFromCache +## data_storage.removeStorageFromCache removeStorageFromCache(path: string): Promise<void> @@ -277,11 +260,12 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js - let promiserevSt = dataStorage.removeStorageFromCache(path + '/mystore') + let path = '/data/storage/el2/database' + let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') promiserevSt.then(() => { console.info("Removed storage from cache successfully.") }).catch((err) => { @@ -412,7 +396,7 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the data. It cannot be empty.| | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```js @@ -443,7 +427,7 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js @@ -578,7 +562,7 @@ Deletes data with the specified key from this storage object. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the data. It cannot be empty.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```js @@ -608,7 +592,7 @@ Deletes data with the specified key from this storage object. This API uses a pr **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js @@ -646,7 +630,7 @@ Saves the modification of this object to the **Storage** instance and synchroniz **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```js @@ -671,7 +655,7 @@ Saves the modification of this object to the **Storage** instance and synchroniz **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js @@ -709,7 +693,7 @@ Clears this **Storage** object. This API uses an asynchronous callback to return **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```js @@ -734,7 +718,7 @@ Clears this **Storage** object. This API uses a promise to return the result. **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index ffbc73ff530a4d8f9ec39fd6e824760df9448644..25cf9ed242f66a0983303065dcea527989444223 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,5 +1,5 @@ # Display -Provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. +The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. > **NOTE** > @@ -14,11 +14,11 @@ import display from '@ohos.display'; ## DisplayState -Provides the state of a display. +Enumerates the display states. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATE_UNKNOWN | 0 | Unknown.| | STATE_OFF | 1 | The display is shut down.| @@ -56,7 +56,7 @@ Describes the attributes of a display. getDefaultDisplay(callback: AsyncCallback<Display>): void -Obtains the default display object. +Obtains the default display object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -82,7 +82,7 @@ Obtains the default display object. getDefaultDisplay(): Promise<Display> -Obtains the default display object. +Obtains the default display object. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -103,11 +103,31 @@ Obtains the default display object. }); ``` +## display.getDefaultDisplaySync9+ + +getDefaultDisplaySync(): Display + +Obtains the default display object. This API returns the result synchronously. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------------------| ----------------------------------------------| +| [Display](#display) | Default display object.| + +**Example** + +```js +var displayClass = display.getDefaultDisplaySync(); +``` + ## display.getAllDisplay getAllDisplay(callback: AsyncCallback<Array<Display>>): void -Obtains all the display objects. +Obtains all display objects. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -133,7 +153,7 @@ Obtains all the display objects. getAllDisplay(): Promise<Array<Display>> -Obtains all the display objects. +Obtains all display objects. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -158,15 +178,15 @@ Obtains all the display objects. on(type: 'add'|'remove'|'change', callback: Callback<number>): void -Enables listening. +Subscribes to display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Listening type. The available values are as follows:
- **add**: listening for whether a display is added
- **remove**: listening for whether a display is removed
- **change**: listening for whether a display is changed| - | callback | Callback<number> | Yes| Callback used to return the ID of the display.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| +| callback | Callback<number> | Yes| Callback used to return the ID of the display.| **Example** ```js @@ -181,14 +201,14 @@ Enables listening. off(type: 'add'|'remove'|'change', callback?: Callback<number>): void -Disables listening. +Unsubscribes from display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Listening type. The available values are as follows:
- **add**: listening for whether a display is added
- **remove**: listening for whether a display is removed
- **change**: listening for whether a display is changed| + | type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| | callback | Callback<number> | No| Callback used to return the ID of the display.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index 8612aad1008deb0883598892c8fdbc6e54cec571..dc674978d2c4b9491e860b13f1720787380cc53e 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,6 +1,8 @@ # Distributed Account Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. + +> **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. @@ -11,17 +13,14 @@ import account_distributedAccount from '@ohos.account.distributedAccount'; ``` -## System Capability - -SystemCapability.Account.OsAccount - - ## account_distributedAccount.getDistributedAccountAbility getDistributedAccountAbility(): DistributedAccountAbility Obtains a **DistributedAccountAbility** instance. +**System capability**: SystemCapability.Account.OsAccount + - Return value | Type| Description| | -------- | -------- | @@ -42,6 +41,8 @@ queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): v Obtains distributed account information. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Account.OsAccount + **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) - Parameters @@ -63,7 +64,9 @@ Obtains distributed account information. This API uses an asynchronous callback queryOsAccountDistributedInfo(): Promise<DistributedInfo> -Obtains distributed account information. This API uses a promise to return the result asynchronously. +Obtains distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) @@ -89,6 +92,8 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall Updates distributed account information. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Account.OsAccount + **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) - Parameters @@ -110,7 +115,9 @@ Updates distributed account information. This API uses an asynchronous callback updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> -Updates distributed account information. This API uses a promise to return the result asynchronously. +Updates distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) @@ -140,10 +147,11 @@ Updates distributed account information. This API uses a promise to return the r Defines distributed OS account information. +**System capability**: SystemCapability.Account.OsAccount -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of a distributed account. It must be a non-null string. | -| id | string | Yes | UID of a distributed account. It must be a non-null string. | -| event | string | Yes | Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | -| scalableData | object | No| Extended information about a distributed account. Customized information is passed in key-value pairs.
Note: This parameter is reserved and not used in query and update methods.| \ No newline at end of file +| name | string | Yes| Name of a distributed account. It must be a non-null string.| +| id | string | Yes| UID of a distributed account. It must be a non-null string.| +| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| scalableData | object | No| Extended information about a distributed account. Customized information is passed in key-value pairs.
Note: This parameter is reserved and not used in query and update methods.| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index d44ba34a8a05de6dea75b8d94965376e668d6bd1..154bba75b0c8172459b41725add26ce2fa96db34 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -1,6 +1,15 @@ # Distributed Data Management -Distributed data management provides collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to the distributed database and perform operations such as adding, deleting, modifying, and querying data in the distributed database. +The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. + +This module provides the following functions: + +- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores. +- [KvStoreResultSet8+](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position. +- [Query8+](#query8): provides methods to query data from the database through a **Query** instance by using predicates. +- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance. +- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device. +- [DeviceKVStore8+ ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device. >**NOTE**
> @@ -18,7 +27,7 @@ import distributedData from '@ohos.data.distributedData'; createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void -Creates a **KVManager** object to manage key-value (KV) stores. This API uses an asynchronous callback to return the result. +Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -26,8 +35,8 @@ Creates a **KVManager** object to manage key-value (KV) stores. This API uses an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** object, including the bundle name and user information of the caller.| -| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** object created.| +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| +| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| **Example** ```js @@ -57,7 +66,7 @@ try { createKVManager(config: KVManagerConfig): Promise<KVManager> -Creates a **KVManager** object to manage KV stores. This API uses a promise to return the result. +Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -65,13 +74,13 @@ Creates a **KVManager** object to manage KV stores. This API uses a promise to r | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** object, including the bundle name and user information of the caller.| +| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| **Return value** | Type| Description| | -------- | -------- | -| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** object created.| +| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| **Example** @@ -104,6 +113,7 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | +| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| @@ -121,11 +131,11 @@ Defines user information. ## UserType -Defines the user type. +Enumerates the user types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name| Default Value| Description| +| Name| Value| Description| | ----- | ------ | ------ | | SAME_USER_ID | 0 | User who logs in to different devices using the same account.| @@ -198,7 +208,7 @@ Creates and obtains a KV store. This API uses a promise to return the result. | Type | Description | | -------------------------------------- | ------------------------ | -| Promise<T> <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.| +| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.| **Example** @@ -241,7 +251,7 @@ Closes a KV store. This API uses an asynchronous callback to return the result. | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | kvStore | [KVStore](#kvstore) | Yes | KV store to close. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -261,7 +271,7 @@ const options = { kvManager.getKVStore('storeId', options, async function (err, store) { console.log('getKVStore success'); kvStore = store; - await kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { + kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { console.log('closeKVStore success'); }); }); @@ -291,7 +301,7 @@ Closes a KV store. This API uses a promise to return the result. | Type | Description | | ------------- | -------------- | -| Promise\ | Promise used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned.| +| Promise\ | Promise that returns no value.| **Example** @@ -311,7 +321,7 @@ const options = { kvManager.getKVStore('storeId', options).then(async (store) => { console.log('getKVStore success'); kvStore = store; - await kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { + kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { console.log('closeKVStore success'); }).catch((err) => { console.log('closeKVStore err ' + JSON.stringify(err)); @@ -339,7 +349,7 @@ Deletes a KV store. This API uses an asynchronous callback to return the result. | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -359,7 +369,7 @@ try { kvManager.getKVStore('store', options, async function (err, store) { console.log('getKVStore success'); kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + kvManager.deleteKVStore('appId', 'storeId', function (err, data) { console.log('deleteKVStore success'); }); }); @@ -388,7 +398,7 @@ Deletes a KV store. This API uses a promise to return the result. | Type | Description | | ------------- | -------------- | -| Promise<void> | Promise used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +| Promise<void> | Promise that returns no value.| **Example** @@ -408,7 +418,7 @@ try { kvManager.getKVStore('storeId', options).then(async (store) => { console.log('getKVStore success'); kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId').then(() => { + kvManager.deleteKVStore('appId', 'storeId').then(() => { console.log('deleteKVStore success'); }).catch((err) => { console.log('deleteKVStore err ' + JSON.stringify(err)); @@ -426,7 +436,7 @@ try { getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void -Obtains the IDs of all the KV stores that are created using [getKVStore](#getkvstore) and have not been deleted using [deleteKVStore](#deletekvstore8). This API uses an asynchronous callback to return the result. +Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -435,7 +445,7 @@ Obtains the IDs of all the KV stores that are created using [getKVStore](#getkvs | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | -| callback | AsyncCallback<void> | Yes |Callback used to return the KV store IDs obtained. | +| callback | AsyncCallback<string[]> | Yes |Callback used to return the KV store IDs obtained. | **Example** @@ -456,7 +466,7 @@ try { getAllKVStoreId(appId: string): Promise<string[]> -Obtains the IDs of all the KV stores that are created using [getKVStore](#getkvstore) and have not been deleted using [deleteKVStore](#deletekvstore8). This API uses a promise to return the result. +Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -495,7 +505,7 @@ try { on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void -Subscribes to the **distributedDataServiceDie** events. This API uses a synchronous callback to return the result. +Subscribes to service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -503,8 +513,8 @@ Subscribes to the **distributedDataServiceDie** events. This API uses a synchron | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Name of the event to subscribe to. The value is **distributedDataServiceDie**, which indicates the service status change event.| -| deathCallback | Callback<void> | Yes | Callback invoked when the distributed data service is dead. | +| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates service status changes.| +| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.| **Example** @@ -527,7 +537,7 @@ try { off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -Unsubscribes from the **distributedDataServiceDie** events. This API uses a synchronous callback to return the result. +Unsubscribes from the service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -535,8 +545,8 @@ Unsubscribes from the **distributedDataServiceDie** events. This API uses a sync | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Name of the event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates the service status change event.| -| deathCallback | Callback<void> | No | Callback used to return the **distributedDataServiceDie** events. | +| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates service status changes.| +| deathCallback | Callback<void> | No | Callback used to return service status changes.| **Example** @@ -559,45 +569,44 @@ try { Provides KV store configuration. -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created. | -| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted. | -| backup | boolean | No|Whether to back up database files. By default, database files are backed up. | -| autoSync | boolean | No|Whether to automatically synchronize database files. By default, database files are not automatically synchronized.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | -| kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.| -| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set. | -| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.| +| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | +| kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| ## KVStoreType -Defines the KV store types. +Enumerates the KV store types. -| Name | Default Value| Description | +| Name | Value| Description | | --- | ---- | ----------------------- | -| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | -| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| +| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| ## SecurityLevel -Defines the KV store security levels. +Enumerates the KV store security levels. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value| Description | +| Name | Value| Description | | --- | ---- | ----------------------- | | NO_LEVEL | 0 | No security level is set for the KV store. | -| S0 | 1 | The KV store security level is public. | -| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. | -| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. | -| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. | -| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. | +| S0 | 1 | The KV store security level is public.| +| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| +| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| +| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| +| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| ## Constants @@ -606,18 +615,18 @@ Defines the KV store constants. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value| Description | +| Name | Value| Description | | --- | ---- | ----------------------- | -| MAX_KEY_LENGTH | 1024 | Maximum length (in bytes) of a key in the KV store. | -| MAX_VALUE_LENGTH | 4194303 | Maximum length (in bytes) of a value in the KV store. | -| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of the device key, in bytes.| -| MAX_STORE_ID_LENGTH | 128 | Maximum length (in bytes) of a KV store ID. | +| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. | +| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the KV store, in bytes. | +| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes.| +| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | | MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.| | MAX_BATCH_SIZE | 128 | Maximum number of batch operations.| ## Schema8+ ## -Defines the schema of a KV store. When creating or opening a KV store, you can create a **Schema** object and put it in [Options](#options). +Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -646,7 +655,7 @@ Represents a **Schema** instance, which provides the methods for defining the va | --- | ---- | ----------------------- | | nullable8+ | boolean | Whether the database field can be null. | | default8+ | string | Default value of a **FieldNode**.| -| type8+ | number | Value to store.| +| type8+ | number | Value of the data type corresponding to the specified node.| ### constructor8+ ### @@ -694,7 +703,7 @@ try { node.appendChild(child1); node.appendChild(child2); node.appendChild(child3); - console.log("appendNode " + node.toJson()); + console.log("appendNode " + JSON.stringify(node)); child1 = null; child2 = null; child3 = null; @@ -707,14 +716,16 @@ try { ## KvStoreResultSet8+ ## -Provides methods to obtain the KV store result set and query or move the data read position. Before calling any method in **KvStoreResultSet**, you must use **KvStore** to create a **KvStore** instance. +Provides methods to obtain the KV store result sets, and query and move the data read position. + +Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. ### getCount8+ ### getCount(): number -Obtains the number of rows in the result set. +Obtains the total number of rows in the result set. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -722,7 +733,7 @@ Obtains the number of rows in the result set. | Type | Description | | ------ | -------------- | -| number |Number of rows obtained. | +| number |Total number of rows obtained. | **Example** @@ -734,7 +745,7 @@ try { console.log('getResultSet succeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet failed:' + err); + console.log('getResultSet failed: ' + err); }); const count = resultSet.getCount(); console.log("getCount succeed:" + count); @@ -767,7 +778,7 @@ try { console.log('getResultSet succeeed.'); resultSet = result; }).catch((err) => { - console.log('getResultSet failed:' + err); + console.log('getResultSet failed: ' + err); }); const position = resultSet.getPosition(); console.log("getPosition succeed:" + position); @@ -781,7 +792,7 @@ try { moveToFirst(): boolean -Moves the data read position to the first row. +Moves the data read position to the first row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -815,7 +826,7 @@ try { moveToLast(): boolean -Moves the data read position to the last row. +Moves the data read position to the last row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -849,7 +860,7 @@ try { moveToNext(): boolean -Moves the data read position to the next row. +Moves the data read position to the next row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -883,7 +894,7 @@ try { moveToPrevious(): boolean -Moves the data read position to the previous row. +Moves the data read position to the previous row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1005,7 +1016,7 @@ Checks whether the data read position is the first row. | Type | Description | | ------ | -------------- | -| boolean |Returns **true** if the data read position is the first row; returns **false** otherwise. | +| boolean |Returns **true** if the first row is being read; returns **false** otherwise. | **Example** @@ -1039,7 +1050,7 @@ Checks whether the data read position is the last row. | Type | Description | | ------ | -------------- | -| boolean |Returns **true** if the data read position is the last row; returns **false** otherwise. | +| boolean |Returns **true** if the last row is being read; returns **false** otherwise. | **Example** @@ -1072,7 +1083,7 @@ Checks whether the data read position is before the first row. | Type | Description | | ------ | -------------- | -| boolean |Returns **true** if the read position is before the first row; returns **false** otherwise. | +| boolean |Returns **true** if the data read position is before the first row; returns **false** otherwise. | **Example** @@ -1132,7 +1143,7 @@ try { getEntry(): Entry -Obtains a KV pair. +Obtains the KV pair from the current position. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1181,7 +1192,7 @@ A constructor used to create a **Schema** instance. reset(): Query -Resets the **Query** object that contains common query options. +Resets the **Query** object. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1212,7 +1223,7 @@ try { equalTo(field: string, value: number|string|boolean): Query -Creates a **Query** object to match the specified field whose value is equal to the specified value. +Creates a **Query** object to match the specified field whose value is equal to the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1227,7 +1238,7 @@ Creates a **Query** object to match the specified field whose value is equal to | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object reset.| +| [Query](#query8) |**Query** object.| **Example** @@ -1262,7 +1273,7 @@ Creates a **Query** object to match the specified field whose value is not equal | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1297,7 +1308,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1332,7 +1343,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1367,7 +1378,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1402,7 +1413,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1424,7 +1435,6 @@ isNull(field: string): Query Creates a **Query** object to match the specified field whose value is **null**. - **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** @@ -1437,7 +1447,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1473,7 +1483,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1508,7 +1518,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1543,7 +1553,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1578,7 +1588,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1606,14 +1616,14 @@ Creates a **Query** object to match the specified field whose value is similar t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes Field to match. It cannot contain '^'. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | string | Yes | String specified.| **Return value** | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1648,7 +1658,7 @@ Creates a **Query** object to match the specified field whose value is not simil | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1742,7 +1752,7 @@ Creates a **Query** object to sort the query results in ascending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1777,7 +1787,7 @@ Creates a **Query** object to sort the query results in descending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1813,15 +1823,17 @@ Creates a **Query** object to specify the number of results and where to start. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** ```js +let total = 10; +let offset = 1; try { let query = new distributedData.Query(); query.notEqualTo("field", "value"); - query.limit("total", "offset"); + query.limit(total, offset); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { @@ -1834,7 +1846,7 @@ try { isNotNull(field: string): Query -Creates a **Query** object with a specified field that is not null. +Creates a **Query** object to match the specified field whose value is not **null**. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1842,13 +1854,13 @@ Creates a **Query** object with a specified field that is not null. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field specified. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | **Return value** | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1876,7 +1888,7 @@ Creates a **Query** object for a query condition group with a left parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1906,7 +1918,7 @@ Creates a **Query** object for a query condition group with a right parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1942,7 +1954,7 @@ Creates a **Query** object with a specified key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -1977,7 +1989,7 @@ Creates a **Query** object with an index preferentially used for query. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -2013,7 +2025,7 @@ Creates a **Query** object with the device ID as the key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object.| **Example** @@ -2032,7 +2044,7 @@ try { getSqlLike():string -Obtains the query statement of this **Query** object. +Obtains the query statement of the **Query** object. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2040,7 +2052,7 @@ Obtains the query statement of this **Query** object. | Type | Description | | ------ | ------- | -| string |Query statement obtained.| +| string |Returns the query statement obtained.| **Example** @@ -2057,7 +2069,9 @@ try { ## KVStore -Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. +Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. + +Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. ### put @@ -2114,7 +2128,7 @@ Adds a KV pair of the specified type to this KV store. This API uses a promise t | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2133,7 +2147,6 @@ try { } ``` - ### delete delete(key: string, callback: AsyncCallback<void>): void @@ -2175,7 +2188,6 @@ try { } ``` - ### delete delete(key: string): Promise<void> @@ -2194,7 +2206,7 @@ Deletes a KV pair from this KV store. This API uses a promise to return the resu | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2218,12 +2230,91 @@ try { } ``` +### delete9+ + +delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>): void + +Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| +| callback | AsyncCallback<void> | Yes |Callback used to return the result. | + +**Example** + +```js +import dataSharePredicates from './@ohos.data.dataSharePredicates'; +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + kvStore.delete(predicates, function (err, data) { + if (err == undefined) { + console.log('delete success'); + } else { + console.log('delete fail' + err); + } + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` + +### delete9+ + +delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> + +Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| + + +**Return value** + +| Type | Description | +| ------ | ------- | +| Promise<void> |Promise used to return the result.| + +**Example** + +```js +import dataSharePredicates from './@ohos.data.dataSharePredicates'; +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let arr = ["name"]; + predicates.inKeys(arr); + kvStore.put("name", "bob").then((data) => { + console.log('put success' + JSON.stringify(data)); + kvStore.delete(predicates).then((data) => { + console.log('delete success'); + }).catch((err) => { + console.log('delete fail' + JSON.stringify(err)); + }); + }) .catch((err) => { + console.log(' put fail' + err); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} + +``` ### on('dataChange') on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data change notifications of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2231,9 +2322,9 @@ Subscribes to data changes of the specified type. This API uses a synchronous ca | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **dataChange**, which indicates the data change event. | +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| +| observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| **Example** @@ -2249,7 +2340,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to data synchronization completion events. This API uses a synchronous callback to return the result. +Subscribes to data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2257,8 +2348,8 @@ Subscribes to data synchronization completion events. This API uses a synchronou | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **syncComplete**, which indicates the synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. | **Example** @@ -2273,7 +2364,7 @@ kvStore.on('syncComplete', function (data) { off(event:'dataChange', observer?: Callback<ChangeNotification>): void -Unsubscribes from data change events. This API uses a synchronous callback to return the result. +Unsubscribes from data change notifications. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2281,8 +2372,8 @@ Unsubscribes from data change events. This API uses a synchronous callback to re | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to unsubscribe from. The value is **dataChange**, which indicates the data change event. | -| observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | +| observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| **Example** @@ -2296,12 +2387,42 @@ kvStore.off('dataChange', function (data) { }); ``` +### off('syncComplete')9+ + +off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void + +Unsubscribes from data change events. This API uses a synchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | +| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | + +**Example** + +```js +let kvStore; +try { + const func = function (data) { + console.log('syncComplete ' + data) + }; + kvStore.on('syncComplete', func); + kvStore.off('syncComplete', func); +}catch(e) { + console.log('syncComplete e ' + e); +} +``` + ### putBatch8+ putBatch(entries: Entry[], callback: AsyncCallback<void>): void -Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result. +Inserts KV pairs to this KV store in batches. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2332,14 +2453,14 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key', function (err,entrys) { + kvStore.getEntries('batch_test_string_key', function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); }); }); }catch(e) { - console.log('PutBatch e ' + e); + console.log('PutBatch e ' + JSON.stringify(e)); } ``` @@ -2348,7 +2469,7 @@ try { putBatch(entries: Entry[]): Promise<void> -Inserts KV pairs in batches to this KV store. This API uses a promise to return the result. +Inserts KV pairs to this KV store in batches. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2362,7 +2483,7 @@ Inserts KV pairs in batches to this KV store. This API uses a promise to return | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2384,7 +2505,7 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key').then((entrys) => { + kvStore.getEntries('batch_test_string_key').then((entrys) => { console.log('getEntries success'); console.log('PutBatch ' + JSON.stringify(entries)); }).catch((err) => { @@ -2394,16 +2515,99 @@ try { console.log('putBatch fail ' + JSON.stringify(err)); }); }catch(e) { - console.log('PutBatch e ' + e); + console.log('PutBatch e ' + JSON.stringify(e)); +} +``` + +### putBatch9+ + +putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void + +Writes values to this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| value |Array[<ValuesBucket>]()[] | Yes |Values to write. | +| callback |Asyncallback<void> |Yes |Callback used to return the result.| + +**Example** + +```js +let kvStore; +try { + let v8Arr = []; + let arr = new Uint8Array([4,5,6,7]); + let vb1 = {key : "name_1", value : 32} + let vb2 = {key : "name_2", value : arr}; + let vb3 = {key : "name_3", value : "lisi"}; + + v8Arr.push(vb1); + v8Arr.push(vb2); + v8Arr.push(vb3); + kvStore.putBatch(v8Arr, async function (err,data) { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('putBatch e ' + JSON.stringify(e)); } ``` +### putBatch9+ + +putBatch(value: Array<ValuesBucket>): Promise<void> + +Writes values of the **valuesbucket** type to this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| value |Array<[ValuesBucket>](#)[] | Yes |Values to write. | + +**Return value** + +| Type | Description | +| ------ | ------- | +| Promise<void> |Promise used to return the result.| + +**Example** + +```js +let kvStore; +try { + let v8Arr = []; + let arr = new Uint8Array([4,5,6,7]); + let vb1 = {key : "name_1", value : 32} + let vb2 = {key : "name_2", value : arr}; + let vb3 = {key : "name_3", value : "lisi"}; + + v8Arr.push(vb1); + v8Arr.push(vb2); + v8Arr.push(vb3); + kvStore.putBatch(v8Arr).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('PutBatch e ' + JSON.stringify(e)); +} + +``` ### deleteBatch8+ deleteBatch(keys: string[], callback: AsyncCallback<void>): void -Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. +Deletes KV pairs from this KV store in batches. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2436,7 +2640,7 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - await kvStore.deleteBatch(keys, async function (err,data) { + kvStore.deleteBatch(keys, async function (err,data) { console.log('deleteBatch success'); }); }); @@ -2450,7 +2654,7 @@ try { deleteBatch(keys: string[]): Promise<void> -Deletes KV pairs in batches from this KV store. This API uses a promise to return the result. +Deletes KV pairs from this KV store in batches. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2464,7 +2668,7 @@ Deletes KV pairs in batches from this KV store. This API uses a promise to retur | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2488,7 +2692,7 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - await kvStore.deleteBatch(keys).then((err) => { + kvStore.deleteBatch(keys).then((err) => { console.log('deleteBatch success'); }).catch((err) => { console.log('deleteBatch fail ' + JSON.stringify(err)); @@ -2544,7 +2748,7 @@ try { console.log('startTransaction success'); let entries = putBatchString(10, 'batch_test_string_key'); console.log('entries: ' + JSON.stringify(entries)); - await kvStore.putBatch(entries, async function (err,data) { + kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); }); }); @@ -2566,7 +2770,7 @@ Starts the transaction in this KV store. This API uses a promise to return the r | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2593,7 +2797,7 @@ try { commit(callback: AsyncCallback<void>): void -Commits the transaction in this KV store. This API uses an asynchronous callback to return the result. +Submits the transaction in this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2625,7 +2829,7 @@ try { commit(): Promise<void> -Commits the transaction in this KV store. This API uses a promise to return the result. +Submits the transaction in this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2633,7 +2837,7 @@ Commits the transaction in this KV store. This API uses a promise to return the | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2695,7 +2899,7 @@ Rolls back the transaction in this KV store. This API uses a promise to return t | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2717,7 +2921,7 @@ try { enableSync(enabled: boolean, callback: AsyncCallback<void>): void -Sets data synchronization, which can be enabled or disable. This API uses an asynchronous callback to return the result. +Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2750,7 +2954,7 @@ try { enableSync(enabled: boolean): Promise<void> -Enables or disables data synchronization. This API uses a promise to return the result. +Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2764,7 +2968,7 @@ Enables or disables data synchronization. This API uses a promise to return the | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2834,7 +3038,7 @@ Sets the data synchronization range. This API uses a promise to return the resul | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2856,11 +3060,11 @@ try { ## SubscribeType -Defines the subscription type. +Enumerates the subscription types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----- | ------ | ----------------------- | | SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. | | SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. | @@ -2893,24 +3097,22 @@ Defines the KV pairs stored in the KV store. ## Value -Defines the value in a KV pair. +Defines the **value** object in a KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Type |Readable |Writable | Description | | ----- | ------- | -----| ------|------------------------ | | type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | +| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value. | ## ValueType -Enumerates the types of values in KV pairs. - -These value types can be used only by internal applications. +Enumerates the data types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----- | ------ | ----------------------- | | STRING |0 |String. | | INTEGER |1 |Integer. | @@ -2922,13 +3124,17 @@ These value types can be used only by internal applications. ## SingleKVStore -Provides methods to query and synchronize data in a single KV store. This class inherits from **KVStore**. Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** object. +Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). + +Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices. + +Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. ### get get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void -Obtains the value of a specified key. This API uses an asynchronous callback to return the result. +Obtains the value of the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2937,7 +3143,7 @@ Obtains the value of a specified key. This API uses an asynchronous callback to | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback used to return the value obtained. | +| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. | **Example** @@ -2966,7 +3172,7 @@ try { get(key: string): Promise<Uint8Array | string | boolean | number> -Obtains the value of a specified key. This API uses a promise to return the result. +Obtains the value of the specified key. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3009,7 +3215,7 @@ try { getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void -Obtains the KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. +Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3018,7 +3224,7 @@ Obtains the KV pairs that match the specified key prefix. This API uses an async | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | **Example** @@ -3039,7 +3245,7 @@ try { } kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - await kvStore.getEntries('batch_test_number_key', function (err,entrys) { + kvStore.getEntries('batch_test_number_key', function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); @@ -3055,7 +3261,7 @@ try { getEntries(keyPrefix: string): Promise<Entry[]> -Obtains the KV pairs that match the specified key prefix. This API uses a promise to return the result. +Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3091,7 +3297,7 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key').then((entrys) => { + kvStore.getEntries('batch_test_string_key').then((entrys) => { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); @@ -3121,7 +3327,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | +| query |[Query](#query8) | Yes |Key prefix to match. | | callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** @@ -3147,7 +3353,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getEntries(query, function (err,entrys) { + kvStore.getEntries(query, function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); @@ -3183,6 +3389,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses a **Example** ```js +let kvStore; try { var arr = new Uint8Array([21,31]); let entries = []; @@ -3202,7 +3409,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { + kvStore.getEntries(query).then((entrys) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -3221,7 +3428,7 @@ try { getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the result set with the specified key prefix from this single KV store. This API uses an asynchronous callback to return the result. +Obtains the result set with the specified prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3230,7 +3437,7 @@ Obtains the result set with the specified key prefix from this single KV store. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match.| -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback used to return the result set obtained.| +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set obtained.| **Example** @@ -3252,7 +3459,7 @@ try { } kvStore.putBatch(entries, async function (err, data) { console.log('GetResultSet putBatch success'); - await kvStore.getResultSet('batch_test_string_key', async function (err, result) { + kvStore.getResultSet('batch_test_string_key', async function (err, result) { console.log('GetResultSet getResultSet succeed.'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { @@ -3270,7 +3477,7 @@ try { getResultSet(keyPrefix: string): Promise<KvStoreResultSet> -Obtains the result set with the specified key prefix from this single KV store. This API uses a promise to return the result. +Obtains the result set with the specified prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3330,7 +3537,7 @@ try { getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3339,7 +3546,7 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |Query | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback used to return the **KvStoreResultSet** object obtained.| +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| **Example** @@ -3363,7 +3570,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSet(query, async function (err, result) { + kvStore.getResultSet(query, async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; }); @@ -3378,7 +3585,7 @@ try { getResultSet(query: Query): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3430,11 +3637,86 @@ try { } ``` +### getResultSet9+ ### + +getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void + +Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultsetsup8sup)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| + +**Example** + +```js +import dataSharePredicates from './@ohos.data.dataSharePredicates'; +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates, async function (err, result) { + console.log(' GetResultSet success'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + console.log(' closeResultSet success'); + }) + }); +}catch(e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +### getResultSet9+ ### + +getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> + +Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| predicates |[Predicates](#) | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | + +**Return value** + +| Type | Description | +| ------ | ------- | +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| + +**Example** + +```js +import dataSharePredicates from './@ohos.data.dataSharePredicates'; +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates) .then((result) => { + console.log(' GetResultSet success'); + resultSet = result; + kvStore.closeResultSet(resultSet, fun ction (err, data) { + console.log(' closeResultSet success'); + }) + }); +}catch(e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` ### closeResultSet8+ ### closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3468,7 +3750,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3482,7 +3764,7 @@ Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet]( | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -3514,7 +3796,7 @@ Obtains the number of results that matches the specified **Query** object. This | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | +| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | **Example** @@ -3537,7 +3819,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSize(query, async function (err, resultSize) { + kvStore.getResultSize(query, async function (err, resultSize) { console.log('getResultSet succeed.'); }); }); @@ -3627,12 +3909,12 @@ try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { console.log('put success'); const deviceid = 'no_exist_device_id'; - await kvStore.removeDeviceData(deviceid, async function (err,data) { + kvStore.removeDeviceData(deviceid, async function (err,data) { if (err == undefined) { console.log('removeDeviceData success'); } else { console.log('removeDeviceData fail'); - await kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { + kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData get success'); }); } @@ -3662,7 +3944,7 @@ Deletes data of a device. This API uses a promise to return the result. | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -3697,7 +3979,7 @@ try { on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the synchronization completion events. This API uses a synchronous callback to return the result. +Subscribes to the data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3705,8 +3987,8 @@ Subscribes to the synchronization completion events. This API uses a synchronous | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **syncComplete**, which indicates the synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return the synchronization result. | **Example** @@ -3733,7 +4015,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization completion events. This API uses a synchronous callback to return the result. +Unsubscribes from the data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3741,7 +4023,7 @@ Unsubscribes from the synchronization completion events. This API uses a synchro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to unsubscribe from. The value is **syncComplete**, which indicates the synchronization complete event. | +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | | syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | **Example** @@ -3759,12 +4041,64 @@ try { } ``` +### on('dataChange')9+ ### + +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void + +Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | +| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| + +**Example** + +```js +let kvStore; +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); + +``` + +### off('dataChange')9+ ### + +off(event:'dataChange', listener?: Callback<ChangeNotification>): void + +Unsubscribes from the data change events. This API uses a synchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| + +**Example** + +```js +let kvStore; +kvStore.on('dataChange', function (data) { + console.log("callback call data: " + data); +}); +kvStore.off('dataChange', function (data) { + console.log("callback call data: " + data); +}); +``` +### sync7+ -### sync sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void -Manually triggers KV store synchronization synchronously. For details about the synchronization mode of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3774,8 +4108,8 @@ Manually triggers KV store synchronization synchronously. For details about the | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |IDs of the devices to be synchronized. These devices must be in the same networking environment. | -| mode |[SyncMode](#syncmode) | Yes |Data synchronization mode. | +| deviceIdList |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | +| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | | allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -3785,6 +4119,48 @@ let kvStore; kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); ``` +### sync9+ +sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void + +Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | +| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | +| query |[Query](#querysup8sup) | Yes |**Query** object to match. | +| delayMs |number | No |Allowed synchronization delay time, in ms. | + +**Example** + +```js +let kvstore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { + console.log('Sync put success'); + const devices = ['deviceList']; + const mode = distributedData.SyncMode.PULL_ONLY; + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + kvStore.sync(devices, query, PULL_ONLY , 1000); + }); +}catch(e) { + console.log('Sync e' + e); +} +``` + ### setSyncParam8+ ### setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void @@ -3834,7 +4210,7 @@ Sets the default delay allowed for KV store synchronization. This API uses a pro | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -3865,7 +4241,7 @@ Obtains the security level of this KV store. This API uses an asynchronous callb | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback used to return the security level obtained. | +| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback invoked to return the security level obtained. | **Example** @@ -3893,7 +4269,7 @@ Obtains the security level of this KV store. This API uses a promise to return t | Type | Description | | ------ | ------- | -|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the value obtained.| +|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| **Example** @@ -3913,13 +4289,19 @@ try { ## DeviceKVStore8+ ## -Provides methods to manage distributed data by device in the distributed system. This class inherits from **KVStore** and provides data query and synchronization methods. Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. +Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore). + +Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. + +For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. + +Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. ### get8+ ### get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void -Obtains the string value that matches the specified key for a device. This API uses an asynchronous callback to return the result. +Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -3954,7 +4336,7 @@ try{ get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> -Obtains the string value that matches the specified key for a device. This API uses a promise to return the result. +Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -3969,7 +4351,7 @@ Obtains the string value that matches the specified key for a device. This API u | Type | Description | | ------ | ------- | -|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the value obtained.| +|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.| **Example** @@ -3998,7 +4380,7 @@ try { getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void -Obtains the KV pairs that match the specified key prefix for a device. This API uses an asynchronous callback to return the result. +Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4030,7 +4412,7 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - await kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { + kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); @@ -4046,7 +4428,7 @@ try { getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> -Obtains the KV pairs that match the specified key prefix for a device. This API uses a promise to return the result. +Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4083,7 +4465,7 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - await kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { + kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); @@ -4137,11 +4519,10 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - expect(err == undefined).assertTrue(); const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - await kvStore.getEntries(query, function (err,entrys) { + kvStore.getEntries(query, function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); @@ -4197,7 +4578,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { + kvStore.getEntries(query).then((entrys) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -4216,7 +4597,7 @@ try { getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void -Obtains the KV pairs that match the specified **Query** object for a device. This API uses an asynchronous callback to return the result. +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4226,7 +4607,7 @@ Obtains the KV pairs that match the specified **Query** object for a device. Thi | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | **Example** @@ -4249,11 +4630,10 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - expect(err == undefined).assertTrue(); var query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); - await kvStore.getEntries('localDeviceId', query, function (err,entrys) { + kvStore.getEntries('localDeviceId', query, function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); @@ -4270,7 +4650,7 @@ try { getEntries(deviceId: string, query: Query): Promise<Entry[]> -Obtains the KV pairs that match the specified **Query** object for a device. This API uses a promise to return the result. +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4311,7 +4691,7 @@ try { var query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); - await kvStore.getEntries('localDeviceId', query).then((entrys) => { + kvStore.getEntries('localDeviceId', query).then((entrys) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -4330,7 +4710,7 @@ try { getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified key prefix for a device. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4340,7 +4720,7 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -4351,7 +4731,7 @@ try { kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); @@ -4365,7 +4745,7 @@ try { getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified key prefix for a device. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4409,7 +4789,7 @@ try { getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4418,7 +4798,7 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -4443,10 +4823,10 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - await kvStore.getResultSet(query, async function (err, result) { + kvStore.getResultSet(query, async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); @@ -4461,7 +4841,7 @@ try { getResultSet(query: Query): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4525,7 +4905,7 @@ try { getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified **Query** object for a device. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4535,7 +4915,7 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -4559,10 +4939,10 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSet('localDeviceId', query, async function (err, result) { + kvStore.getResultSet('localDeviceId', query, async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); @@ -4577,7 +4957,7 @@ try { getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified **Query** object for a device. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4643,7 +5023,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4678,7 +5058,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4692,7 +5072,7 @@ Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet]( | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -4725,7 +5105,7 @@ Obtains the number of results that matches the specified **Query** object. This | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | +| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | **Example** @@ -4749,7 +5129,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - await kvStore.getResultSize(query, async function (err, resultSize) { + kvStore.getResultSize(query, async function (err, resultSize) { console.log('getResultSet succeed.'); }); }); @@ -4819,7 +5199,7 @@ try { getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; -Obtains the number of results that matches the specified **Query** object for a device. This API uses an asynchronous callback to return the result. +Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4829,7 +5209,7 @@ Obtains the number of results that matches the specified **Query** object for a | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | +| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | **Example** @@ -4852,7 +5232,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { + kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { console.log('getResultSet succeed.'); }); }); @@ -4866,7 +5246,7 @@ try { getResultSize(deviceId: string, query: Query): Promise<number> -Obtains the number of results that matches the specified **Query** object for a device. This API uses a promise to return the result. +Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4922,7 +5302,7 @@ try { removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void -Removes data of a device from this KV store. This API uses an asynchronous callback to return the result. +Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4943,12 +5323,12 @@ try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData put success'); const deviceid = 'no_exist_device_id'; - await kvStore.removeDeviceData(deviceid, async function (err,data) { + kvStore.removeDeviceData(deviceid, async function (err,data) { if (err == undefined) { console.log('removeDeviceData success'); } else { console.log('removeDeviceData fail'); - await kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData get success'); }); } @@ -4964,7 +5344,7 @@ try { removeDeviceData(deviceId: string): Promise<void> -Removes data of a device from this KV store. This API uses a promise to return the result. +Deletes data of the specified device from this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4978,7 +5358,7 @@ Removes data of a device from this KV store. This API uses a promise to return t | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -5013,7 +5393,7 @@ try { sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void -Manually triggers KV store synchronization synchronously. For details about the synchronization mode of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -5048,11 +5428,53 @@ try { } ``` +### sync9+ ### + +sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void + +Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| +| query |[Query](#query8) | Yes | **Query** object to match.| +| delayMs |number | No |Allowed synchronization delay time, in ms. | + +**Example** + +```js +let kvstore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { + console.log('Sync put success'); + const devices = ['deviceList']; + const mode = distributedData.SyncMode.PULL_ONLY; + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + kvStore.sync(devices, query, 1000); + }); +}catch(e) { + console.log('Sync e' + e); +} +``` + ### on('syncComplete')8+ ### on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the synchronization completion events. This API uses a synchronous callback to return the result. +Subscribes to the data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5060,12 +5482,13 @@ Subscribes to the synchronization completion events. This API uses a synchronous | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **syncComplete**, which indicates the synchronization complete event.| +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates the data synchronization complete event.| | syncCallback |Callback | Yes |Callback used to return the synchronization result. | **Example** ```js +let kvStore; const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; const VALUE_TEST_FLOAT_ELEMENT = 321.12; try { @@ -5087,7 +5510,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization completion events. This API uses a synchronous callback to return the result. +Unsubscribes from the synchronization complete events. This API uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5095,7 +5518,7 @@ Unsubscribes from the synchronization completion events. This API uses a synchro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to unsubscribe from. The value is **syncComplete**, which indicates the synchronization complete event.| +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.| | syncCallback |Callback9+ ### + +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void + +Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | +| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| + +**Example** + +```js +let kvStore; +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); +``` + + +### off('dataChange')9+ ### + +off(event:'dataChange', listener?: Callback<ChangeNotification>): void + +Unsubscribes from the data change events. This API uses a synchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| + +**Example** + +```js +let kvStore; +kvStore.on('dataChange', function (data) { + console.log("callback call data: " + data); +}); +kvStore.off('dataChange', function (data) { + console.log("callback call data: " + data); +}); +``` ## SyncMode @@ -5120,7 +5595,7 @@ Enumerates the synchronization modes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----- | ------ | ----------------------- | | PULL_ONLY |0 |Pull data from the peer end to the local end only.| | PUSH_ONLY |1 |Push data from the local end to the peer end only.| diff --git a/en/application-dev/reference/apis/js-apis-document.md b/en/application-dev/reference/apis/js-apis-document.md index 2291c064820b4dc1782937351fe6ec27180042ec..458685119e17635f1b5af60e27910808bf8f99d6 100644 --- a/en/application-dev/reference/apis/js-apis-document.md +++ b/en/application-dev/reference/apis/js-apis-document.md @@ -1,6 +1,6 @@ # File Interaction -> **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. > - The APIs of this module will be deprecated and are not recommended for use. An exception will be thrown if any of the APIs is called. @@ -12,28 +12,29 @@ import document from '@ohos.document'; ## document.choose -choose(type:string[]): Promise<string> +choose(types? : string[]): Promise<string> Chooses a file of the specified type using the file manager. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** -| Name| Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------- | -| type | string[] | No | Type of the file to choose. | + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------------- | + | types | string[] | No | Type of the file to choose.| -- Return value +**Return value** -| Type | Description | -| --------------------- | -------------- | -| Promise<string> | Promise used to return the result. An error code is returned. | + | Type | Description | + | --------------------- | -------------- | + | Promise<string> | Promise used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.choose(type); + let types = []; + document.choose(types); ``` ## document.choose @@ -41,91 +42,98 @@ choose(callback:AsyncCallback<string>): void Chooses a file using the file manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned. | + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | ---------------------------- | + | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.choose(function(err, uri) { + let uri = ""; + document.choose(function(err, uri) { // Do something with the URI. }); ``` ## document.choose -choose(type:string[], callback:AsyncCallback<string>): void +choose(types:string[], callback:AsyncCallback<string>): void -Chooses a file of the specified type using the file manager. This API uses an asynchronous callback to return the result. +Chooses a file using the file manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ---------------------------- | -| type | string[] | No | Type of the file to choose. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned. | + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | ---------------------------- | + | types | string[] | No | Type of the file to choose.| + | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.choose(type, function(err, uri) { + let types = []; + let uri = ""; + document.choose(types, function(err, uri) { // Do something with the URI. }); ``` ## document.show -show(url:string, type:string):Promise<number> +show(uri:string, type:string):Promise<void> Opens a file. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------- | -| uri | string | Yes | URI of the file to open. | -| type | string | Yes | Type of the file to open. | + | Name| Type | Mandatory| Description | + | ---- | ------ | ---- | ---------------------------- | + | uri | string | Yes | URI of the file to open.| + | type | string | Yes | Type of the file to open.| -- Return value +**Return value** -| Type | Description | -| --------------------- | ------------ | -| Promise<void> | Promise used to return the result. An error code is returned. | + | Type | Description | + | --------------------- | ------------ | + | Promise<void> | Promise used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.show(uri, type); + let type = ""; + let uri = ""; + document.show(uri, type); ``` ## document.show -show(url:string, type:string, callback:AsyncCallback<void>): void +show(uri:string, type:string, callback:AsyncCallback<void>): void Opens a file. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ---------------------------- | -| uri | string | Yes | URI of the file to open. | -| type | string | Yes | Type of the file to open. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | ---------------------------- | + | uri | string | Yes | URI of the file to open.| + | type | string | Yes | Type of the file to open.| + | callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | -- Example +**Example** ```js - await document.show(uri, type, function(err) { + let type = ""; + let uri = ""; + document.show(uri, type, function(err) { //do something }); - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 204144be86343fe9d62876a2da879c3ef35262bb..133276e077b78d22fb2c06222ba067611f9ee3c7 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -1,9 +1,10 @@ # File Management +The fileio module provides APIs for file storage and management, including basic file management, directory management, file information statistics, and stream read and write. + > **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. -This module provides file storage functions. It provides JS I/O APIs, including basic file management APIs, basic directory management APIs, statistical APIs for obtaining file information, and streaming APIs for reading and writing files. ## Modules to Import @@ -14,30 +15,22 @@ import fileio from '@ohos.fileio'; ## Guidelines -Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). - -Application sandbox path of a file or directory = Application directory + File name or directory name - -For example, if the application directory obtained by using **getOrCreateLocalDir** is **dir** and the file name is **xxx.txt**, the application sandbox path of the file is as follows: - -```js -let path = dir + "/xxx.txt"; -``` - - -The file descriptor is as follows: - - -```js -let fd = fileio.openSync(path); -``` +Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: + ```js + import featureAbility from '@ohos.ability.featureAbility'; + let context = featureAbility.getContext(); + let path = ''; + context.getFilesDir().then((data) => { + path = data; + }) + ``` ## fileio.stat stat(path: string): Promise<Stat> -Asynchronously obtains file information. This API uses a promise to return the result. +Obtains file information. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -45,7 +38,7 @@ Asynchronously obtains file information. This API uses a promise to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| **Return value** @@ -54,11 +47,12 @@ Asynchronously obtains file information. This API uses a promise to return the r | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| **Example** + ```js fileio.stat(path).then(function(stat){ - console.info("getFileInfo successfully:"+ JSON.stringify(stat)); + console.info("Got file info:"+ JSON.stringify(stat)); }).catch(function(err){ - console.info("getFileInfo failed with error:"+ err); + console.info("Failed to get file info. Error:"+ err); }); ``` @@ -67,17 +61,19 @@ Asynchronously obtains file information. This API uses a promise to return the r stat(path:string, callback:AsyncCallback<Stat>): void -Asynchronously obtains file information. This API uses a callback to return the result. +Obtains file information. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| **Example** + ```js fileio.stat(path, function (err, stat) { // Example code in Stat @@ -94,17 +90,20 @@ Synchronously obtains file information. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| **Return value** + | Type | Description | | ------------- | ---------- | | [Stat](#stat) | File information obtained.| **Example** + ```js let stat = fileio.statSync(path); // Example code in Stat @@ -115,26 +114,29 @@ Synchronously obtains file information. opendir(path: string): Promise<Dir> -Asynchronously opens a directory. This API uses a promise to return the result. +Opens a file directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------ | | path | string | Yes | Application sandbox path of the directory to open.| **Return value** + | Type | Description | | -------------------------- | -------- | - | Promise<[Dir](#dir)> | A **Dir** instance corresponding to the directory.| + | Promise<[Dir](#dir)> | Promise used to return the **Dir** object.| **Example** + ```js fileio.opendir(path).then(function(dir){ - console.info("opendir successfully:"+ JSON.stringify(dir)); + console.info("Directory opened:"+ JSON.stringify(dir)); }).catch(function(err){ - console.info("opendir failed with error:"+ err); + console.info("Failed to open the directory. Error:"+ err); }); ``` @@ -143,7 +145,7 @@ Asynchronously opens a directory. This API uses a promise to return the result. opendir(path: string, callback: AsyncCallback<Dir>): void -Asynchronously opens a directory. This API uses a callback to return the result. +Opens a file directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -155,6 +157,7 @@ Asynchronously opens a directory. This API uses a callback to return the result. | callback | AsyncCallback<[Dir](#dir)> | Yes | Callback invoked when the directory is open asynchronously. | **Example** + ```js fileio.opendir(path, function (err, dir) { // Example code in Dir struct @@ -179,11 +182,13 @@ Synchronously opens a directory. | path | string | Yes | Application sandbox path of the directory to open.| **Return value** + | Type | Description | | ----------- | -------- | | [Dir](#dir) | A **Dir** instance corresponding to the directory.| **Example** + ```js let dir = fileio.opendirSync(path); // Example code in Dir struct @@ -195,7 +200,7 @@ Synchronously opens a directory. access(path: string, mode?: number): Promise<void> -Asynchronously checks whether the current process can access a file. This API uses a promise to return the result. +Checks whether the current process can access a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -203,20 +208,22 @@ Asynchronously checks whether the current process can access a file. This API us | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.access(path).then(function() { - console.info("access successfully"); + console.info("Access successful"); }).catch(function(err){ - console.info("access failed with error:"+ err); + console.info("Access failed. Error:"+ err); }); ``` @@ -225,18 +232,20 @@ Asynchronously checks whether the current process can access a file. This API us access(path: string, mode: number, callback: AsyncCallback<void>): void -Asynchronously checks whether the current process can access a file. This API uses a callback to return the result. +Checks whether the current process can access a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously checked. | **Example** + ```js fileio.access(path, function (err) { // Do something. @@ -253,17 +262,19 @@ Synchronously checks whether the current process can access the specified file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| **Example** + ```js try { fileio.accessSync(path); } catch(err) { - console.info("accessSync failed with error:"+ err); + console.info("accessSync failed. Error:"+ err); } ``` @@ -272,27 +283,30 @@ Synchronously checks whether the current process can access the specified file. close(fd: number):Promise<void> -Asynchronously closes a file. This API uses a promise to return the result. +Closes a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the file to close.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let fd = fileio.openSync(path); fileio.close(fd).then(function(){ - console.info("close file successfully"); + console.info("File closed"); }).catch(function(err){ - console.info("close file failed with error:"+ err); + console.info("Failed to close the file. Error:"+ err); }); ``` @@ -301,17 +315,19 @@ Asynchronously closes a file. This API uses a promise to return the result. close(fd: number, callback:AsyncCallback<void>): void -Asynchronously closes a file. This API uses a callback to return the result. +Closes a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ------------ | | fd | number | Yes | File descriptor of the file to close.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| **Example** + ```js let fd = fileio.openSync(path); fileio.close(fd, function (err) { @@ -329,11 +345,13 @@ Synchronously closes a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the file to close.| **Example** + ```js fileio.closeSync(fd); ``` @@ -343,21 +361,23 @@ Synchronously closes a file. close(): Promise<void> -Asynchronously closes the stream. This API uses a promise to return the result. +Closes the stream. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.close().then(function(){ - console.info("close file stream successfully"); + console.info("File stream closed"); }).catch(function(err){ - console.info("close file stream failed with error:"+ err); + console.info("Failed to close the file stream. Error:"+ err); }); ``` @@ -366,16 +386,18 @@ Asynchronously closes the stream. This API uses a promise to return the result. close(callback: AsyncCallback<void>): void -Asynchronously closes the stream. This API uses a callback to return the result. +Closes the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ------------- | | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| **Example** + ```js fileio.close(function(err){ // Do something. @@ -387,11 +409,12 @@ Asynchronously closes the stream. This API uses a callback to return the result. copyFile(src:string | number, dest:string | number, mode?:number):Promise<void> -Asynchronously copies a file. This API uses a promise to return the result. +Copies a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | -------------------------- | ---- | ---------------------------------------- | | src | string \| number | Yes | Path or file descriptor of the file to copy. | @@ -399,16 +422,18 @@ Asynchronously copies a file. This API uses a promise to return the result. | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.copyFile(src, dest).then(function(){ - console.info("copyFile successfully"); + console.info("File copied"); }).catch(function(err){ - console.info("copyFile failed with error:"+ err); + console.info("Failed to copy the file. Error:"+ err); }); ``` @@ -417,11 +442,12 @@ Asynchronously copies a file. This API uses a promise to return the result. copyFile(src: string | number, dest: string | number, mode: number, callback: AsyncCallback<void>): void -Asynchronously copies a file. This API uses a callback to return the result. +Copies a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | -------------------------- | ---- | ---------------------------------------- | | src | string \| number | Yes | Path or file descriptor of the file to copy. | @@ -430,6 +456,7 @@ Asynchronously copies a file. This API uses a callback to return the result. | callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | **Example** + ```js fileio.copyFile(src, dest, function (err) { // Do something. @@ -446,6 +473,7 @@ Synchronously copies a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | -------------------------- | ---- | ---------------------------------------- | | src | string \| number | Yes | Path or file descriptor of the file to copy. | @@ -453,6 +481,7 @@ Synchronously copies a file. | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| **Example** + ```js fileio.copyFileSync(src, dest); ``` @@ -462,27 +491,30 @@ Synchronously copies a file. mkdir(path:string, mode?: number): Promise<void> -Asynchronously creates a directory. This API uses a promise to return the result. +Creates a directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the directory to create. | +| path | string | Yes | Application sandbox path of the directory. | | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.mkdir(path).then(function() { - console.info("mkdir successfully"); + console.info("Directory created"); }).catch(function (error){ - console.info("mkdir failed with error:"+ error); + console.info("Failed to create the directory. Error:"+ error); }); ``` @@ -491,21 +523,23 @@ Asynchronously creates a directory. This API uses a promise to return the result mkdir(path: string, mode: number, callback: AsyncCallback<void>): void -Asynchronously creates a directory. This API uses a callback to return the result. +Creates a directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the directory to create. | +| path | string | Yes | Application sandbox path of the directory. | | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | **Example** + ```js fileio.mkdir(path, function(err) { - console.info("mkdir successfully"); + console.info("Directory created"); }); ``` @@ -519,12 +553,14 @@ Synchronously creates a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the directory to create. | +| path | string | Yes | Application sandbox path of the directory. | | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Example** + ```js fileio.mkdirSync(path); ``` @@ -534,28 +570,31 @@ Synchronously creates a directory. open(path: string, flags?: number, mode?: number): Promise<number> -Asynchronously opens a file. This API uses a promise to return the result. +Opens a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | -| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| +| path | string | Yes | Application sandbox path of the file. | +| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Return value** + | Type | Description | | --------------------- | ----------- | - | Promise<number> | File descriptor of the file opened.| + | Promise<number> | Promise used to return the file descriptor of the file opened.| **Example** + ```js fileio.open(path, 0o1, 0o0200).then(function(number){ - console.info("open file successfully"); - }).catch(function(error){ - console.info("open file failed with error:"+ err); + console.info("File opened"); + }).catch(function(err){ + console.info("Failed to open the file. Error:"+ err); }); ``` @@ -564,19 +603,21 @@ Asynchronously opens a file. This API uses a promise to return the result. open(path: string, flags: number, mode: number, callback: AsyncCallback<number>): void -Asynchronously opens a file. This API uses a callback to return the result. +Opens a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | -| flags | number | Yes | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| +| path | string | Yes | Application sandbox path of the file. | +| flags | number | Yes | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| | callback | AsyncCallback <void> | Yes | Callback invoked when the file is open asynchronously. | **Example** + ```js fileio.open(path, 0, function(err, fd) { // Do something. @@ -593,20 +634,31 @@ Synchronously opens a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | -| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| -| mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| +| path | string | Yes | Application sandbox path of the file. | +| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| +| mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o640**: The owner has the read and write permissions, and the user group has the read permission.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| **Return value** + | Type | Description | | ------ | ----------- | | number | File descriptor of the file opened.| **Example** + ```js - let fd = fileio.openSync(path); + let fd = fileio.openSync(path, 0o102, 0o640); + ``` + ```js + let fd = fileio.openSync(path, 0o102, 0o666); + fileio.writeSync(fd, 'hello world'); + let fd1 = fileio.openSync(path, 0o2002); + fileio.writeSync(fd1, 'hello world'); + let num = fileio.readSync(fd1, new ArrayBuffer(4096), {position: 0}); + console.info("num == " + num); ``` @@ -618,11 +670,12 @@ read(fd: number, buffer: ArrayBuffer, options?: { position?: number; }): Promise<ReadOut> -Asynchronously reads data from a file. This API uses a promise to return the result. +Reads data from a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ----------- | ---- | ------------------------------------------------------------ | | fd | number | Yes | File descriptor of the file to read. | @@ -633,17 +686,18 @@ Asynchronously reads data from a file. This API uses a promise to return the res | Type | Description | | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Data read.| + | Promise<[ReadOut](#readout)> | Promise used to return the data read.| **Example** + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); - fileio.read(fd, buf).then(function(readout){ - console.info("read file data successfully"); + fileio.read(fd, buf).then(function(readOut){ + console.info("Read file data"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - }).catch(function(error){ - console.info("read file data failed with error:"+ error); + }).catch(function(err){ + console.info("Failed to read file data. Error:"+ err); }); ``` @@ -656,11 +710,12 @@ read(fd: number, buffer: ArrayBuffer, options: { position?: number; }, callback: AsyncCallback<ReadOut>): void -Asynchronously reads data from a file. This API uses a callback to return the result. +Reads data from a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to read. | @@ -669,12 +724,13 @@ Asynchronously reads data from a file. This API uses a callback to return the re | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously. | **Example** + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); fileio.read(fd, buf, function (err, readOut) { if (readOut) { - console.info("read file data successfully"); + console.info("Read file data"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); } }); @@ -694,6 +750,7 @@ Synchronously reads data from a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------- | ----------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to read. | @@ -701,11 +758,13 @@ Synchronously reads data from a file. | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | ------ | -------- | | number | Length of the data read.| **Example** + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); @@ -717,26 +776,29 @@ Synchronously reads data from a file. rmdir(path: string): Promise<void> -Asynchronously deletes a directory. This API uses a promise to return the result. +Deletes a directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the directory to delete.| +| path | string | Yes | Application sandbox path of the directory.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.rmdir(path).then(function() { - console.info("rmdir successfully"); + console.info("Directory deleted"); }).catch(function(err){ - console.info("rmdir failed with error:"+ err); + console.info("Failed to delete the directory. Error:"+ err); }); ``` @@ -745,21 +807,23 @@ Asynchronously deletes a directory. This API uses a promise to return the result rmdir(path: string, callback:AsyncCallback<void>): void -Asynchronously deletes a directory. This API uses a callback to return the result. +Deletes a directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the directory to delete.| +| path | string | Yes | Application sandbox path of the directory.| | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously. | **Example** + ```js fileio.rmdir(path, function(err){ // Do something. - console.info("rmdir successfully"); + console.info("Directory deleted"); }); ``` @@ -773,11 +837,13 @@ Synchronously deletes a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the directory to delete.| +| path | string | Yes | Application sandbox path of the directory.| **Example** + ```js fileio.rmdirSync(path); ``` @@ -787,26 +853,29 @@ Synchronously deletes a directory. unlink(path:string): Promise<void> -Asynchronously deletes a file. This API uses a promise to return the result. +Deletes a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the file to delete.| +| path | string | Yes | Application sandbox path of the file.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.unlink(path).then(function(){ - console.info("remove file successfully"); + console.info("File deleted"); }).catch(function(error){ - console.info("remove file failed with error:"+ error); + console.info("Failed to delete the file. Error:"+ error); }); ``` @@ -815,20 +884,22 @@ Asynchronously deletes a file. This API uses a promise to return the result. unlink(path:string, callback:AsyncCallback<void>): void -Asynchronously deletes a file. This API uses a callback to return the result. +Deletes a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the file to delete.| +| path | string | Yes | Application sandbox path of the file.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | **Example** + ```js fileio.unlink(path, function(err) { - console.info("remove file successfully"); + console.info("File deleted"); }); ``` @@ -842,11 +913,13 @@ Synchronously deletes a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the file to delete.| +| path | string | Yes | Application sandbox path of the file.| **Example** + ```js fileio.unlinkSync(path); ``` @@ -861,11 +934,12 @@ write(fd: number, buffer: ArrayBuffer | string, options?: { encoding?: string; }): Promise<number> -Asynchronously writes data into a file. This API uses a promise to return the result. +Writes data into a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to write. | @@ -873,17 +947,19 @@ Asynchronously writes data into a file. This API uses a promise to return the re | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| **Return value** + | Type | Description | | --------------------- | -------- | - | Promise<number> | Length of the data written in the file.| + | Promise<number> | Promise used to return the length of the data written.| **Example** + ```js - let fd = fileio.openSync(fpath, 0o100 | 0o2, 0o666); + let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world").then(function(number){ - console.info("write data to file successfully and size is:"+ number); + console.info("Data written to file and size is:"+ number); }).catch(function(err){ - console.info("write data to file failed with error:"+ err); + console.info("Failed to write data to the file. Error:"+ err); }); ``` @@ -897,11 +973,12 @@ write(fd: number, buffer: ArrayBuffer | string, options: { encoding?: string; }, callback: AsyncCallback<number>): void -Asynchronously writes data into a file. This API uses a callback to return the result. +Writes data into a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to write. | @@ -910,11 +987,12 @@ Asynchronously writes data into a file. This API uses a callback to return the r | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Example** + ```js let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (bytesWritten) { - console.info("write data to file successfully and size is:"+ bytesWritten); + console.info("Data written to file and size is:"+ bytesWritten); } }); ``` @@ -934,6 +1012,7 @@ Synchronously writes data into a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to write. | @@ -941,11 +1020,13 @@ Synchronously writes data into a file. | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| **Return value** + | Type | Description | | ------ | -------- | | number | Length of the data written in the file.| **Example** + ```js let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); let num = fileio.writeSync(fd, "hello, world"); @@ -956,27 +1037,30 @@ Synchronously writes data into a file. hash(path: string, algorithm: string): Promise<string> -Asynchronously calculates the hash value of a file. This API uses a promise to return the result. +Calculates the hash value of a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| **Return value** + | Type | Description | | --------------------- | -------------------------- | - | Promise<string> | Promise used to return the hash value of the file. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + | Promise<string> | Promise used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| **Example** + ```js fileio.hash(path, "sha256").then(function(str){ - console.info("calculate file hash successfully:"+ str); + console.info("Calculated file hash:"+ str); }).catch(function(error){ - console.info("calculate file hash failed with error:"+ err); + console.info("Failed to calculate the file hash. Error:"+ err); }); ``` @@ -985,22 +1069,24 @@ Asynchronously calculates the hash value of a file. This API uses a promise to r hash(path: string, algorithm: string, callback: AsyncCallback<string>): void -Asynchronously calculates the hash value of a file. This API uses a callback to return the result. +Calculates the hash value of a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | --------- | --------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| -| callback | AsyncCallback<string> | Yes | Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| +| callback | AsyncCallback<string> | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| **Example** + ```js - fileio.hash(fpath, "sha256", function(err, hashStr) { + fileio.hash(path, "sha256", function(err, hashStr) { if (hashStr) { - console.info("calculate file hash successfully:"+ hashStr); + console.info("Calculated file hash:"+ hashStr); } }); ``` @@ -1010,27 +1096,30 @@ Asynchronously calculates the hash value of a file. This API uses a callback to chmod(path: string, mode: number):Promise<void> -Asynchronously changes the file permissions based on its path. This API uses a promise to return the result. +Changes file permissions. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.chmod(path, mode).then(function() { - console.info("chmod successfully"); + console.info("File permissions changed"); }).catch(function(err){ - console.info("chmod failed with error:"+ err); + console.info("Failed to change file permissions. Error:"+ err); }); ``` @@ -1039,18 +1128,20 @@ Asynchronously changes the file permissions based on its path. This API uses a p chmod(path: string, mode: number, callback: AsyncCallback<void>): void -Asynchronously changes the file permissions based on its path. This API uses a callback to return the result. +Changes file permissions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | **Example** + ```js fileio.chmod(path, mode, function (err) { // Do something. @@ -1062,19 +1153,21 @@ Asynchronously changes the file permissions based on its path. This API uses a c chmodSync(path: string, mode: number): void -Synchronously changes the file permissions based on its path. +Synchronously changes file permissions. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Example** + ```js - fileio.chmodSync(fpath, mode); + fileio.chmodSync(path, mode); ``` @@ -1082,26 +1175,29 @@ Synchronously changes the file permissions based on its path. fstat(fd: number): Promise<Stat> -Asynchronously obtains file information based on the file descriptor. This API uses a promise to return the result. +Obtains file information based on the file descriptor. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the target file.| **Return value** + | Type | Description | | ---------------------------- | ---------- | - | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| + | Promise<[Stat](#stat)> | Promise used to return the file information.| **Example** + ```js fileio.fstat(fd).then(function(stat){ - console.info("fstat successfully:"+ JSON.stringify(stat)); + console.info("File information obtained:"+ JSON.stringify(stat)); }).catch(function(err){ - console.info("fstat failed with error:"+ err); + console.info("Failed to obtain file information. Error:"+ err); }); ``` @@ -1110,17 +1206,19 @@ Asynchronously obtains file information based on the file descriptor. This API u fstat(fd: number, callback: AsyncCallback<Stat>): void -Asynchronously obtains file information based on the file descriptor. This API uses a callback to return the result. +Obtains file information based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------- | ---- | ---------------- | | fd | number | Yes | File descriptor of the target file. | | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| **Example** + ```js let fd = fileio.openSync(path); fileio.fstat(fd, function (err) { @@ -1138,16 +1236,19 @@ Synchronously obtains file information based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the target file.| **Return value** + | Type | Description | | ------------- | ---------- | | [Stat](#stat) | File information obtained.| **Example** + ```js let fd = fileio.openSync(path); let stat = fileio.fstatSync(fd); @@ -1158,26 +1259,29 @@ Synchronously obtains file information based on the file descriptor. ftruncate(fd: number, len?: number): Promise<void> -Asynchronously truncates a file based on the file descriptor. This API uses a promise to return the result. +Truncates a file based on the file descriptor. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------- | | fd | number | Yes | File descriptor of the file to truncate. | - | len | number | Yes | File length, in bytes, after truncation.| + | len | number | No | File length, in bytes, after truncation.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let fd = fileio.openSync(path); fileio.ftruncate(fd, 5).then(function(err) { - console.info("File truncated successfully."); + console.info("File truncated"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); }); @@ -1188,18 +1292,20 @@ Asynchronously truncates a file based on the file descriptor. This API uses a pr ftruncate(fd: number, len: number, callback:AsyncCallback<void>): void -Asynchronously truncates a file based on the file descriptor. This API uses a callback to return the result. +Truncates a file based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------- | | fd | number | Yes | File descriptor of the file to truncate. | | len | number | Yes | File length, in bytes, after truncation.| - | callback | AsyncCallback<void> | Yes | Callback invoked when the file is truncated asynchronously. | + | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** + ```js fileio.ftruncate(fd, len, function(err){ // Do something. @@ -1216,12 +1322,14 @@ Synchronously truncates a file based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------- | | fd | number | Yes | File descriptor of the file to truncate. | | len | number | No | File length, in bytes, after truncation.| **Example** + ```js fileio.ftruncateSync(fd, len); ``` @@ -1231,25 +1339,28 @@ Synchronously truncates a file based on the file descriptor. truncate(path: string, len?: number): Promise<void> -Asynchronously truncates a file based on its path. This API uses a promise to return the result. +Truncates a file based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | | path | string | Yes | Application sandbox path of the file to truncate. | -| len | number | Yes | File length, in bytes, after truncation.| +| len | number | No | File length, in bytes, after truncation.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.truncate(path, len).then(function(){ - console.info("File truncated successfully."); + console.info("File truncated"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); }); @@ -1260,18 +1371,20 @@ Asynchronously truncates a file based on its path. This API uses a promise to re truncate(path: string, len: number, callback:AsyncCallback<void>): void -Asynchronously truncates a file based on its path. This API uses a callback to return the result. +Truncates a file based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to truncate. | +| path | string | Yes | Application sandbox path of the file to truncate.| | len | number | Yes | File length, in bytes, after truncation.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is truncated asynchronously. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** + ```js fileio.truncate(path, len, function(err){ // Do something. @@ -1288,12 +1401,14 @@ Synchronously truncates a file based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to be truncate. | +| path | string | Yes | Application sandbox path of the file to truncate.| | len | number | No | File length, in bytes, after truncation.| **Example** + ```js fileio.truncateSync(path, len); ``` @@ -1307,27 +1422,30 @@ readText(filePath: string, options?: { encoding?: string; }): Promise<string> -Asynchronously reads the text of a file. This API uses a promise to return the result. +Reads the text content of a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| **Return value** + | Type | Description | | --------------------- | ---------- | - | Promise<string> | Promise used to return the content of the file read.| + | Promise<string> | Promise used to return the content read.| **Example** + ```js fileio.readText(path).then(function(str) { - console.info("readText successfully:"+ str); + console.info("Read file text:"+ str); }).catch(function(err){ - console.info("readText failed with error:"+ err); + console.info("Failed to read text. Error:"+ err); }); ``` @@ -1340,18 +1458,20 @@ readText(filePath: string, options: { encoding?: string; }, callback: AsyncCallback<string>): void -Asynchronously reads the text of a file. This API uses a callback to return the result. +Reads the text content of a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | -| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| -| callback | AsyncCallback<string> | Yes | Callback invoked when the file is read asynchronously. | +| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
-  **encoding**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| +| callback | AsyncCallback<string> | Yes | Callback used to return the content read. | **Example** + ```js fileio.readText(path, function(err, str){ // Do something. @@ -1372,17 +1492,20 @@ Synchronously reads the text of a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filePath | string | Yes | Application sandbox path of the file to be read. | +| filePath | string | Yes | Application sandbox path of the file to read. | | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| **Return value** + | Type | Description | | ------ | -------------------- | | string | Promise used to return the content of the file read.| **Example** + ```js let str = fileio.readTextSync(path, {position: 1, length: 3}); ``` @@ -1392,24 +1515,27 @@ Synchronously reads the text of a file. lstat(path: string): Promise<Stat> -Asynchronously obtains link information. This API uses a promise to return the result. +Obtains link information. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| path | string | Yes | Application sandbox path of the target file, pointing to the link.| +| path | string | Yes | Application sandbox path of the target file.| **Return value** + | Type | Description | | ---------------------------- | ---------- | - | Promise<[Stat](#stat)> | Promise used to return the link information obtained.| + | Promise<[Stat](#stat)> | Promise used to return the link information obtained. For details, see [Stat](#stat).| **Example** + ```js fileio.lstat(path).then(function(stat){ - console.info("Link status obtained:"+ number); + console.info("Got link info:"+ JSON.stringify(stat)); }).catch(function(err){ console.info("Failed to obtain the link status. Error:"+ err); }); @@ -1420,17 +1546,19 @@ Asynchronously obtains link information. This API uses a promise to return the r lstat(path:string, callback:AsyncCallback<Stat>): void -Asynchronously obtains link information. This API uses a callback to return the result. +Obtains link information. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | -------------------------------------- | -| path | string | Yes | Application sandbox path of the target file, pointing to the link.| -| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the link information obtained. | +| path | string | Yes | Application sandbox path of the target file.| +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback used to return the link information obtained. | **Example** + ```js fileio.lstat(path, function (err, stat) { // Do something. @@ -1447,16 +1575,19 @@ Synchronously obtains the link information. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| path | string | Yes | Application sandbox path of the target file, pointing to the link.| +| path | string | Yes | Application sandbox path of the target file.| **Return value** + | Type | Description | | ------------- | ---------- | | [Stat](#stat) | Link information obtained.| **Example** + ```js let stat = fileio.lstatSync(path); ``` @@ -1470,25 +1601,28 @@ read(buffer: ArrayBuffer, options?: { length?: number; }): Promise<ReadOut> -Asynchronously reads data from a file. This API uses a promise to return the result. +Reads data from a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ----------- | ---- | ------------------------------------------------------------ | | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
Constraints: offset + length <= Buffer size| **Return value** + | Type | Description | | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Data read.| + | Promise<[ReadOut](#readout)> | Promise used to return the data read.| **Example** + ```js fileio.read(new ArrayBuffer(4096)).then(function(readout){ - console.info("read file data successfully"); + console.info("Read file data"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); }).catch(function(err){ console.info("Failed to read file data. Error:"+ err); @@ -1504,11 +1638,12 @@ read(buffer: ArrayBuffer, options: { length?: number; }, callback: AsyncCallback<ReadOut>): void -Asynchronously reads data from a file. This API uses a callback to return the result. +Reads data from a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | @@ -1516,11 +1651,12 @@ Asynchronously reads data from a file. This API uses a callback to return the re | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously from the file. | **Example** + ```js let buf = new ArrayBuffer(4096); fileio.read(buf, function (err, readOut) { if (readOut) { - console.info("read file data successfully"); + console.info("Read file data"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); } }); @@ -1531,27 +1667,30 @@ Asynchronously reads data from a file. This API uses a callback to return the re rename(oldPath: string, newPath: string): Promise<void> -Asynchronously renames a file. This API uses a promise to return the result. +Renames a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| | newPath | String | Yes | Application sandbox path of the file renamed. | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.rename(oldPath, newPath).then(function() { - console.info("rename successfully"); + console.info("File renamed"); }).catch(function(err){ - console.info("rename failed with error:"+ err); + console.info("Failed to rename the file. Error:"+ err); }); ``` @@ -1560,18 +1699,20 @@ Asynchronously renames a file. This API uses a promise to return the result. rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void -Asynchronously renames a file. This API uses a callback to return the result. +Renames a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| -| newPath | String | Yes | Application sandbox path of the file renamed. | +| newPath | String | Yes | Application sandbox path of the file renamed. | | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | **Example** + ```js fileio.rename(oldPath, newPath, function(err){ }); @@ -1587,12 +1728,14 @@ Synchronously renames a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| | newPath | String | Yes | Application sandbox path of the file renamed. | **Example** + ```js fileio.renameSync(oldPath, newPath); ``` @@ -1602,26 +1745,29 @@ Synchronously renames a file. fsync(fd: number): Promise<void> -Asynchronously synchronizes a file. This API uses a promise to return the result. +Flushes data of a file to disk. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the file to synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.fsync(fd).then(function(){ - console.info("sync data successfully"); + console.info("Data flushed"); }).catch(function(err){ - console.info("sync data failed with error:"+ err); + console.info("Failed to flush data. Error:"+ err); }); ``` @@ -1630,17 +1776,19 @@ Asynchronously synchronizes a file. This API uses a promise to return the result fsync(fd: number, callback: AsyncCallback<void>): void -Asynchronously synchronizes a file. This API uses a callback to return the result. +Flushes data of a file to disk. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | --------------- | - | fd | number | Yes | File descriptor of the file to synchronize. | + | fd | number | Yes | File descriptor of the file to flush. | | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is synchronized in asynchronous mode.| **Example** + ```js fileio.fsync(fd, function(err){ // Do something. @@ -1652,18 +1800,20 @@ Asynchronously synchronizes a file. This API uses a callback to return the resul fsyncSync(fd: number): void -Synchronizes a file in synchronous mode. +Flushes data of a file to disk in synchronous mode. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the file to synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Example** + ```js - fileio.fyncsSync(fd); + fileio.fsyncSync(fd); ``` @@ -1671,26 +1821,29 @@ Synchronizes a file in synchronous mode. fdatasync(fd: number): Promise<void> -Asynchronously synchronizes data in a file. This API uses a promise to return the result. +Flushes data of a file to disk. This API uses a promise to return the result. **fdatasync()** is similar to **fsync()**, but does not flush modified metadata unless that metadata is needed. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the file to synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.fdatasync(fd).then(function(err) { - console.info("sync data successfully"); + console.info("Data flushed"); }).catch(function(err){ - console.info("sync data failed with error:"+ err); + console.info("Failed to flush data. Error:"+ err); }); ``` @@ -1699,17 +1852,19 @@ Asynchronously synchronizes data in a file. This API uses a promise to return th fdatasync(fd: number, callback:AsyncCallback<void>): void -Asynchronously synchronizes data in a file. This API uses a callback to return the result. +Flushes data of a file to disk. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ----------------- | | fd | number | Yes | File descriptor of the file to synchronize. | | callback | AsyncCallback <void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **Example** + ```js fileio.fdatasync (fd, function (err) { // Do something. @@ -1726,11 +1881,13 @@ Synchronizes data in a file in synchronous mode. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the file to synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Example** + ```js let stat = fileio.fdatasyncSync(fd); ``` @@ -1740,27 +1897,30 @@ Synchronizes data in a file in synchronous mode. symlink(target: string, srcPath: string): Promise<void> -Asynchronously creates a symbolic link based on a path. This API uses a promise to return the result. +Creates a symbolic link based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | -| target | string | Yes | Application sandbox path of the symbolic link. | -| srcPath | string | Yes | Application sandbox path of the referenced file or directory contained in the symbolic link.| +| target | string | Yes | Application sandbox path of the target file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link file.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.symlink(target, srcPath).then(function() { - console.info("symlink successfully"); + console.info("Symbolic link created"); }).catch(function(err){ - console.info("symlink failed with error:"+ err); + console.info("Failed to create the symbolic link. Error:"+ err); }); ``` @@ -1769,18 +1929,20 @@ Asynchronously creates a symbolic link based on a path. This API uses a promise symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void -Asynchronously creates a symbolic link based on a path. This API uses a callback to return the result. +Creates a symbolic link based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------- | -| target | string | Yes | Application sandbox path of the symbolic link. | -| srcPath | string | Yes | Application sandbox path of the referenced file or directory contained in the symbolic link. | +| target | string | Yes | Application sandbox path of the target file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link file. | | callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| **Example** + ```js fileio.symlink(target, srcPath, function (err) { // Do something. @@ -1797,12 +1959,14 @@ Synchronously creates a symbolic link based on a specified path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | -| target | string | Yes | Application sandbox path of the symbolic link. | -| srcPath | string | Yes | Application sandbox path the referenced file or directory contained in the symbolic link.| +| target | string | Yes | Application sandbox path of the target file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link file.| **Example** + ```js fileio.symlinkSync(target, srcPath); ``` @@ -1812,29 +1976,32 @@ Synchronously creates a symbolic link based on a specified path. chown(path: string, uid: number, gid: number): Promise<void> -Asynchronously changes the file owner based on its path. This API uses a promise to return the result. +Changes the file owner based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New user ID (UID). | | gid | number | Yes | New group ID (GID). | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let stat = fileio.statSync(path); fileio.chown(path, stat.uid, stat.gid).then(function(){ - console.info("chown successfully"); + console.info("File owner changed"); }).catch(function(err){ - console.info("chown failed with error:"+ err); + console.info("Failed to change the file owner. Error:"+ err); }); ``` @@ -1843,21 +2010,23 @@ Asynchronously changes the file owner based on its path. This API uses a promise chown(path: string, uid: number, gid: number, callback: AsyncCallback<void>): void -Asynchronously changes the file owner based on its path. This API uses a callback to return the result. +Changes the file owner based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| **Example** + ```js - let stat = fileio.statSync(fpath) + let stat = fileio.statSync(path) fileio.chown(path, stat.uid, stat.gid, function (err){ // Do something. }); @@ -1873,15 +2042,17 @@ Synchronously changes the file owner based on its path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | **Example** + ```js - let stat = fileio.statSync(fpath) + let stat = fileio.statSync(path) fileio.chownSync(path, stat.uid, stat.gid); ``` @@ -1890,26 +2061,29 @@ Synchronously changes the file owner based on its path. mkdtemp(prefix: string): Promise<string> -Asynchronously creates a temporary directory. This API uses a promise to return the result. +Creates a temporary directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** - | Name | Description | + + | Type | Description | | --------------------- | ---------- | - | Promise<string> | Unique path generated.| + | Promise<string> | Promise used to return the unique directory generated.| **Example** + ```js fileio.mkdtemp(path + "XXXX").then(function(path){ - console.info("mkdtemp successfully:"+ path); + console.info("Temporary directory created:"+ path); }).catch(function(err){ - console.info("mkdtemp failed with error:"+ err); + console.info("Failed to create a temporary directory. Error:"+ err); }); ``` @@ -1918,17 +2092,19 @@ Asynchronously creates a temporary directory. This API uses a promise to return mkdtemp(prefix: string, callback: AsyncCallback<string>): void -Asynchronously creates a temporary directory. This API uses a callback to return the result. +Creates a temporary directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | --------------------------- | | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | **Example** + ```js fileio.mkdtemp(path + "XXXX", function (err, res) { // Do something. @@ -1945,16 +2121,19 @@ Synchronously creates a temporary directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** - | Name | Description | + + | Type | Description | | ------ | ---------- | | string | Unique path generated.| **Example** + ```js let res = fileio.mkdtempSync(path + "XXXX"); ``` @@ -1964,27 +2143,30 @@ Synchronously creates a temporary directory. fchmod(fd: number, mode: number): Promise<void> -Asynchronously changes the file permissions based on the file descriptor. This API uses a promise to return the result. +Changes file permissions based on the file descriptor. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Return value** - | Name | Description | + + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.fchmod(fd, mode).then(function() { - console.info("chmod successfully"); + console.info("File permissions changed"); }).catch(function(err){ - console.info("chmod failed with error:"+ err); + console.info("Failed to change file permissions. Error:"+ err); }); ``` @@ -1993,11 +2175,12 @@ Asynchronously changes the file permissions based on the file descriptor. This A fchmod(fd: number, mode: number, callback: AsyncCallback<void>): void -Asynchronously changes the file permissions based on the file descriptor. This API uses a callback to return the result. +Changes file permissions based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | @@ -2005,6 +2188,7 @@ Asynchronously changes the file permissions based on the file descriptor. This A | callback | AsyncCallback <void> | Yes | Callback invoked when the file permissions are changed asynchronously. | **Example** + ```js fileio.fchmod(fd, mode, function (err) { // Do something. @@ -2021,12 +2205,14 @@ Synchronously changes the file permissions based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Example** + ```js fileio.fchmodSync(fd, mode); ``` @@ -2036,27 +2222,30 @@ Synchronously changes the file permissions based on the file descriptor. createStream(path: string, mode: string): Promise<Stream> -Asynchronously opens a stream based on the file path. This API uses a promise to return the result. +Opens a file stream based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** + | Type | Description | | --------------------------------- | --------- | | Promise<[Stream](#stream7)> | Promise used to return the result.| **Example** + ```js fileio.createStream(path, "r+").then(function(stream){ - console.info("createStream successfully"); + console.info("Stream opened"); }).catch(function(err){ - console.info("createStream failed with error:"+ err); + console.info("Failed to create the stream. Error:"+ err); }); ``` @@ -2065,20 +2254,22 @@ Asynchronously opens a stream based on the file path. This API uses a promise to createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void -Asynchronously opens a stream based on the file path. This API uses a callback to return the result. +Opens a file stream based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| | callback | AsyncCallback<[Stream](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. | **Example** + ```js - fileio.createStream(path, mode, function(err, stream){ + fileio.createStream(path, "r+", function(err, stream){ // Do something. }); ``` @@ -2093,17 +2284,20 @@ Synchronously opens a stream based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** - | Name | Description | + + | Type | Description | | ------------------ | --------- | | [Stream](#stream7) | Stream opened.| **Example** + ```js let ss = fileio.createStreamSync(path, "r+"); ``` @@ -2113,27 +2307,31 @@ Synchronously opens a stream based on the file path. fdopenStream(fd: number, mode: string): Promise<Stream> -Asynchronously opens a stream based on the file descriptor. This API uses a promise to return the result. +Opens a file stream based on the file descriptor. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** - | Name | Description | + + | Type | Description | | --------------------------------- | --------- | | Promise<[Stream](#stream7)> | Promise used to return the result.| **Example** + ```js - fileio.fdopenStream(fd, mode).then(function(stream){ - console.info("openStream successfully"); + let fd = fileio.openSync(path); + fileio.fdopenStream(fd, "r+").then(function(stream){ + console.info("Stream opened"); }).catch(function(err){ - console.info("openStream failed with error:"+ err); + console.info("Failed to open the stream. Error:"+ err); }); ``` @@ -2142,11 +2340,12 @@ Asynchronously opens a stream based on the file descriptor. This API uses a prom fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void -Asynchronously opens a stream based on the file descriptor. This API uses a callback to return the result. +Opens a file stream based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | @@ -2154,8 +2353,10 @@ Asynchronously opens a stream based on the file descriptor. This API uses a call | callback | AsyncCallback <[Stream](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. | **Example** + ```js - fileio.fdopenStream(fd, mode, function (err, stream) { + let fd = fileio.openSync(path); + fileio.fdopenStream(fd, "r+", function (err, stream) { // Do something. }); ``` @@ -2170,18 +2371,22 @@ Synchronously opens a stream based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** + | Type | Description | | ------------------ | --------- | | [Stream](#stream7) | Stream opened.| **Example** + ```js + let fd = fileio.openSync(path); let ss = fileio.fdopenStreamSync(fd, "r+"); ``` @@ -2190,11 +2395,12 @@ Synchronously opens a stream based on the file descriptor. fchown(fd: number, uid: number, gid: number): Promise<void> -Asynchronously changes the file owner based on the file descriptor. This API uses a promise to return the result. +Changes the file owner based on the file descriptor. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the target file.| @@ -2202,17 +2408,19 @@ Asynchronously changes the file owner based on the file descriptor. This API use | gid | number | Yes | New GID. | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let stat = fileio.statSync(path); fileio.fchown(fd, stat.uid, stat.gid).then(function() { - console.info("chown successfully"); + console.info("File owner changed"); }).catch(function(err){ - console.info("chown failed with error:"+ err); + console.info("Failed to change the file owner. Error:"+ err); }); ``` @@ -2221,11 +2429,12 @@ Asynchronously changes the file owner based on the file descriptor. This API use fchown(fd: number, uid: number, gid: number, callback: AsyncCallback<void>): void -Asynchronously changes the file owner based on the file descriptor. This API uses a callback to return the result. +Changes the file owner based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | --------------- | | fd | number | Yes | File descriptor of the target file. | @@ -2234,8 +2443,9 @@ Asynchronously changes the file owner based on the file descriptor. This API use | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| **Example** + ```js - let stat = fileio.statSync(fpath); + let stat = fileio.statSync(path); fileio.fchown(fd, stat.uid, stat.gid, function (err){ // Do something. }); @@ -2251,6 +2461,7 @@ Synchronously changes the file owner based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the target file.| @@ -2258,8 +2469,9 @@ Synchronously changes the file owner based on the file descriptor. | gid | number | Yes | New GID. | **Example** + ```js - let stat = fileio.statSync(fpath); + let stat = fileio.statSync(path); fileio.fchownSync(fd, stat.uid, stat.gid); ``` @@ -2268,29 +2480,32 @@ Synchronously changes the file owner based on the file descriptor. lchown(path: string, uid: number, gid: number): Promise<void> -Asynchronously changes the file owner based on the file path, changes the owner of the symbolic link (not the referenced file), and returns the result in a promise. +Changes the file owner (owner of the symbolic link, not the file referred to by the symbolic link) based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let stat = fileio.statSync(path); fileio.lchown(path, stat.uid, stat.gid).then(function() { - console.info("chown successfully"); + console.info("File owner changed"); }).catch(function(err){ - console.info("chown failed with error:"+ err); + console.info("Failed to change the file owner. Error:"+ err); }); ``` @@ -2299,19 +2514,21 @@ Asynchronously changes the file owner based on the file path, changes the owner lchown(path: string, uid: number, gid: number, callback: AsyncCallback<void>): void -Asynchronously changes the file owner based on the file path, changes the owner of the symbolic link (not the referenced file), and returns the result in a callback. +Changes the file owner (owner of the symbolic link, not the file referred to by the symbolic link) based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| path | string | Yes | Application sandbox path of the file. | | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| **Example** + ```js let stat = fileio.statSync(path); fileio.lchown(path, stat.uid, stat.gid, function (err){ @@ -2329,13 +2546,15 @@ Synchronously changes the file owner based on the file path and changes the owne **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | **Example** + ```js let stat = fileio.statSync(path); fileio.lchownSync(path, stat.uid, stat.gid); @@ -2346,27 +2565,32 @@ Synchronously changes the file owner based on the file path and changes the owne createWatcher(filename: string, events: number, callback: AsyncCallback<number>): Watcher -Asynchronously listens for the changes of a file or directory. This API uses a callback to return the result. +Listens for file or directory changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| filename | string | Yes | Application sandbox path of the target file. | +| filename | string | Yes | Application sandbox path of the file. | | events | Number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| | callback | AsyncCallback<number > | Yes | Called each time a change is detected. | **Return value** - | Name | Description | + + | Type | Description | | -------------------- | ---------- | - | [Watcher](#watcher7) | Instance for listening for a file change event.| + | [Watcher](#watcher7) | Promise used to return the **Watcher** instance.| **Example** + ```js - fileio.createWatcher(filename, events, function(watcher){ - // Do something. + let filename = path +"/test.txt"; + fileio.createWatcher(filename, 1, function(number){ + console.info("Monitoring times: "+number); }); + ``` @@ -2416,11 +2640,13 @@ Checks whether this file is a block special file. A block special file supports **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ---------------- | | boolean | Whether the file is a block special file.| **Example** + ```js let isBLockDevice = fileio.statSync(path).isBlockDevice(); ``` @@ -2435,11 +2661,13 @@ Checks whether this file is a character special file. A character special file s **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ----------------- | | boolean | Whether the file is a character special file.| **Example** + ```js let isCharacterDevice = fileio.statSync(path).isCharacterDevice(); ``` @@ -2454,11 +2682,13 @@ Checks whether this file is a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ------------- | | boolean | Whether the file is a directory.| **Example** + ```js let isDirectory = fileio.statSync(path).isDirectory(); ``` @@ -2473,11 +2703,13 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------------- | | boolean | Whether the file is an FIFO.| **Example** + ```js let isFIFO = fileio.statSync(path).isFIFO(); ``` @@ -2492,13 +2724,15 @@ Checks whether this file is a regular file. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------- | | boolean | Whether the file is a regular file.| **Example** + ```js - let isFile = fileio.statSync(fpath).isFile(); + let isFile = fileio.statSync(path).isFile(); ``` @@ -2511,11 +2745,13 @@ Checks whether this file is a socket. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | -------------- | | boolean | Whether the file is a socket.| **Example** + ```js let isSocket = fileio.statSync(path).isSocket(); ``` @@ -2530,11 +2766,13 @@ Checks whether this file is a symbolic link. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------- | | boolean | Whether the file is a symbolic link.| **Example** + ```js let isSymbolicLink = fileio.statSync(path).isSymbolicLink(); ``` @@ -2549,13 +2787,20 @@ Listens for the changes of a file. You can call the **Watcher.stop()** method sy stop(): Promise<void> -Asynchronously stops **watcher**. This API uses a promise to return the result. +Stops the **watcher** instance. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - fileio.stop(); + let filename = path +"/test.txt"; + let watcher = await fileio.createWatcher(filename, 1, function(number){ + console.info("Monitoring times: "+number); + }); + watcher.stop().then(function(){ + console.info("Watcher stopped"); + }); ``` @@ -2563,49 +2808,55 @@ Asynchronously stops **watcher**. This API uses a promise to return the result. stop(callback: AsyncCallback<void>): void -Asynchronously stops **watcher**. This API uses a callback to return the result. +Stops the **watcher** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked when **watcher** is stopped asynchronously.| **Example** + ```js - fileio.stop(function(err){ - // Do something. + let filename = path +"/test.txt"; + let watcher = await fileio.createWatcher(filename, 1, function(number){ + console.info("Monitoring times: "+number); }); + watcher.stop(function(){ + console.info("Watcher stopped"); + }) ``` +## Stream - -## Stream7+ - -File stream. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. +Provides file stream management. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. ### close7+ close(): Promise<void> -Asynchronously closes the stream. This API uses a promise to return the result. +Closes the stream. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------------------- | ------------- | | Promise<void> | Promise used to return the stream close result.| **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.close().then(function(){ - console.info("close fileStream successfully"); + console.info("Stream closed"); }).catch(function(err){ - console.info("close fileStream failed with error:"+ err); + console.info("Failed to close the file stream. Error:"+ err); }); ``` @@ -2614,20 +2865,22 @@ Asynchronously closes the stream. This API uses a promise to return the result. close(callback: AsyncCallback<void>): void -Asynchronously closes the stream. This API uses a callback to return the result. +Closes the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ------------- | | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.close(function (err) { - // do something + // Do something }); ``` @@ -2641,8 +2894,9 @@ Synchronously closes the stream. **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.closeSync(); ``` @@ -2651,22 +2905,24 @@ Synchronously closes the stream. flush(): Promise<void> -Asynchronously flushes the stream. This API uses a promise to return the result. +Flushes the stream. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------------------- | ------------- | | Promise<void> | Promise used to return the stream flushing result.| **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.flush().then(function (){ - console.info("flush successfully"); + console.info("Stream flushed"); }).catch(function(err){ - console.info("flush failed with error:"+ err); + console.info("Failed to flush the stream. Error:"+ err); }); ``` @@ -2675,20 +2931,22 @@ Asynchronously flushes the stream. This API uses a promise to return the result. flush(callback: AsyncCallback<void>): void -Asynchronously flushes the stream. This API uses a callback to return the result. +Flushes the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | -------------- | | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.flush(function (err) { - // do something + // Do something }); ``` @@ -2702,8 +2960,9 @@ Synchronously flushes the stream. **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.flushSync(); ``` @@ -2717,28 +2976,31 @@ write(buffer: ArrayBuffer | string, options?: { encoding?: string; }): Promise<number> -Asynchronously writes data into the stream. This API uses a promise to return the result. +Writes data into the stream. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | --------------------- | -------- | - | Promise<number> | Length of the data written in the file.| + | Promise<number> | Promise used to return the length of the data written.| **Example** + ```js - let ss= fileio.createStreamSync(fpath, "r+"); + let ss= fileio.createStreamSync(path, "r+"); ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ - console.info("write successfully and size is:"+ number); + console.info("Data written to the stream. Size is:"+ number); }).catch(function(err){ - console.info("write failed with error:"+ err); + console.info("Failed to write data to the stream. Error:"+ err); }); ``` @@ -2752,11 +3014,12 @@ write(buffer: ArrayBuffer | string, options: { encoding?: string; }, callback: AsyncCallback<number>): void -Asynchronously writes data into the stream. This API uses a callback to return the result. +Writes data into the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | @@ -2764,12 +3027,13 @@ Asynchronously writes data into the stream. This API uses a callback to return t | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Example** + ```js - let ss= fileio.createStreamSync(fpath, "r+"); + let ss= fileio.createStreamSync(path, "r+"); ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { if (bytesWritten) { - // do something - console.info("write successfully and size is:"+ bytesWritten); + // Do something + console.info("Data written to the stream. Size is:"+ bytesWritten); } }); ``` @@ -2789,19 +3053,22 @@ Synchronously writes data into the stream. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | ------ | -------- | | number | Length of the data written in the file.| **Example** + ```js - let ss= fileio.createStreamSync(fpath,"r+"); + let ss= fileio.createStreamSync(path,"r+"); let num = ss.writeSync("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}); ``` @@ -2814,29 +3081,32 @@ read(buffer: ArrayBuffer, options?: { length?: number; }): Promise<ReadOut> -Asynchronously reads data from the stream. This API uses a promise to return the result. +Reads data from the stream. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ------- | ----------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Data read.| + | Promise<[ReadOut](#readout)> | Promise used to return the data read.| **Example** + ```js - let ss = fileio.createStreamSync(fpath, "r+"); + let ss = fileio.createStreamSync(path, "r+"); ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ - console.info("read data successfully"); + console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); }).catch(function(err){ - console.info("read data failed with error:"+ err); + console.info("Failed to read data. Error:"+ err); }); ``` @@ -2849,11 +3119,12 @@ read(buffer: ArrayBuffer, options: { length?: number; }, callback: AsyncCallback<ReadOut>): void -Asynchronously reads data from the stream. This API uses a callback to return the result. +Reads data from the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | @@ -2861,11 +3132,12 @@ Asynchronously reads data from the stream. This API uses a callback to return th | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when data is read asynchronously from the stream. | **Example** + ```js - let ss = fileio.createStreamSync(fpath, "r+"); + let ss = fileio.createStreamSync(path, "r+"); ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { if (readOut) { - console.info("read data successfully"); + console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); } }); @@ -2898,8 +3170,9 @@ Synchronously reads data from the stream. | number | Length of the data read.| **Example** + ```js - let ss = fileio.createStreamSync(fpath, "r+"); + let ss = fileio.createStreamSync(path, "r+"); let num = ss.readSync(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}); ``` @@ -2913,22 +3186,24 @@ Manages directories. Before calling a method of the **Dir** class, use the [open read(): Promise<Dirent> -Asynchronously reads the next directory entry. This API uses a promise to return the result. +Reads the next directory entry. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | -------------------------------- | ------------- | - | Promise<[Dirent](#dirent)> | Directory entry that is read asynchronously.| + | Promise<[Dirent](#dirent)> | Promise used to return the directory entry read.| **Example** + ```js let dir = fileio.opendirSync(path); dir.read().then(function (dirent){ - console.log("read successfully:"+JSON.stringify(dirent)); + console.log("Read the next directory entry:"+JSON.stringify(dirent)); }).catch(function(err){ - console.info("read failed with error:"+ err); + console.info("Failed to read the next directory entry. Error:"+ err); }); ``` @@ -2937,22 +3212,24 @@ Asynchronously reads the next directory entry. This API uses a promise to return read(callback: AsyncCallback<Dirent>): void -Asynchronously reads the next directory entry. This API uses a callback to return the result. +Reads the next directory entry. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | -------------------------------------- | ---- | ---------------- | | callback | AsyncCallback<[Dirent](#dirent)> | Yes | Callback invoked when the next directory entry is asynchronously read.| **Example** + ```js let dir = fileio.opendirSync(path); dir.read(function (err, dirent) { if (dirent) { - // do something - console.log("read successfully:"+JSON.stringify(dirent)); + // Do something + console.log("Read the next directory entry:"+JSON.stringify(dirent)); } }); ``` @@ -2967,17 +3244,55 @@ Synchronously reads the next directory entry. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ----------------- | -------- | | [Dirent](#dirent) | Directory entry read.| **Example** + ```js let dir = fileio.opendirSync(path); let dirent = dir.readSync(); ``` +### close7+ + +close(): Promise<void> + +Closes a directory. This API uses a promise to return the result. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let dir = fileio.opendirSync(path); + dir.close().then(function(err){ + console.info("close dir successfully"); + }); + ``` + + + ### close7+ + +close(callback: AsyncCallback<void>): void + +Closes a directory. This API uses an asynchronous callback to return the result. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let dir = fileio.opendirSync(path); + dir.close(function(err){ + console.info("close dir successfully"); + }); + ``` + + ### closeSync closeSync(): void @@ -2987,6 +3302,7 @@ Closes a directory. After a directory is closed, the file descriptor in Dir will **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js let dir = fileio.opendirSync(path); dir.closeSync(); @@ -3010,16 +3326,18 @@ Provides information about files and directories. Before calling a method of the isBlockDevice(): boolean -Checks whether the current directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. +Checks whether this directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ---------------- | | boolean | Whether the directory entry is a block special file.| **Example** + ```js let dir = fileio.opendirSync(path); let isBLockDevice = dir.readSync().isBlockDevice(); @@ -3035,11 +3353,13 @@ Checks whether a directory entry is a character special file. A character specia **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ----------------- | | boolean | Whether the directory entry is a character special file.| **Example** + ```js let dir = fileio.opendirSync(path); let isCharacterDevice = dir.readSync().isCharacterDevice(); @@ -3055,11 +3375,13 @@ Checks whether a directory entry is a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ------------- | | boolean | Whether the directory entry is a directory.| **Example** + ```js let dir = fileio.opendirSync(path); let isDirectory = dir.readSync().isDirectory(); @@ -3070,16 +3392,18 @@ Checks whether a directory entry is a directory. isFIFO(): boolean -Checks whether the current directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. +Checks whether this directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------- | | boolean | Whether the directory entry is a FIFO.| **Example** + ```js let dir = fileio.opendirSync(path); let isFIFO = dir.readSync().isFIFO(); @@ -3095,11 +3419,13 @@ Checks whether a directory entry is a regular file. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------- | | boolean | Whether the directory entry is a regular file.| **Example** + ```js let dir = fileio.opendirSync(path); let isFile = dir.readSync().isFile(); @@ -3115,11 +3441,13 @@ Checks whether a directory entry is a socket. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | -------------- | | boolean | Whether the directory entry is a socket.| **Example** + ```js let dir = fileio.opendirSync(dpath); let isSocket = dir.readSync().isSocket(); @@ -3135,11 +3463,13 @@ Checks whether a directory entry is a symbolic link. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------- | | boolean | Whether the directory entry is a symbolic link.| **Example** + ```js let dir = fileio.opendirSync(path); let isSymbolicLink = dir.readSync().isSymbolicLink(); diff --git a/en/application-dev/reference/apis/js-apis-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md index 5d1e0db973a372a82daa363ed62a38177265b5cf..38d6d982683a111a7ef98acfbd0d6f8f8d61ba4d 100644 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ b/en/application-dev/reference/apis/js-apis-filemanager.md @@ -1,11 +1,12 @@ # User File Access and Management + +The fileManager module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user 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. >- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**. -This module provides service APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. - ## Modules to Import ```js @@ -18,20 +19,20 @@ getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> Obtains information about the root album or directory in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +**Parameters** +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -- Return value +**Return value** - | Type| Description| - | --- | -- | - | Promise<[FileInfo](#fileinfo)[]> | Promise used to return the root album or directory information obtained.| +| Type| Description| +| --- | -- | +| Promise<[FileInfo](#fileinfo)[]> | Promise used to return the root album or directory information obtained.| -- Example +**Example** ```js filemanager.getRoot().then((fileInfo) => { @@ -51,25 +52,31 @@ getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) Obtains information about the root album or directory in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------- | ---- | ----------------------------- | - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------- | +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | -- Example +**Example** ```js - filemanager.getRoot((err, fileInfo) => { + let options = { + "dev":{ + "name":"local" + } + }; + filemanager.getRoot(options, (err, fileInfo)=>{ if(Array.isArray(fileInfo)) { for (var i = 0; i < fileInfo.length; i++) { console.log("file:"+JSON.stringify(fileInfo)); } - } + } }); + ``` ## filemanager.listFile @@ -78,34 +85,35 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num Obtains information about the second-level album or files in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | path | string | Yes| URI of the directory to query.| - | type | string | Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - -- Return value +**Parameters** +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| path | string | Yes| URI of the directory to query.| +| type | string | Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - | Type| Description| - | --- | -- | - | Promise<FileInfo[]> | Promise used to return the album or file information obtained.| +**Return value** -- Error - | Error Info| Error Code|Description| - | -- | --- | -- | - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service.| - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +| Type| Description| +| --- | -- | +| Promise<FileInfo[]> | Promise used to return the album or file information obtained.| -- Example +**Error** + +| Error Info| Error Code|Description| +| -- | --- | -- | +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service.| +| Not a directory | 20 | The object specified by the URI is not a directory or album.| + +**Example** ```js // Obtain all files in the directory. // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.uri + let media_path = "" filemanager.listFile(media_path, "file") .then((fileInfo) => { if(Array.isArray(fileInfo)) { @@ -114,7 +122,7 @@ Obtains information about the second-level album or files in asynchronous mode. } } }).catch((err) => { - console.log(err) + console.log("Failed to get file"+err); }); ``` @@ -124,35 +132,52 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num Obtains information about the second-level album or files in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------- | ---- | ------------------------------------------------------------ | - | path | string | Yes | URI of the directory to query. | - | type | string | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the file information obtained. | -- Error +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | URI of the directory to query. | +| type | string | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| +| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - | Error Info | Error Code| Description | - | ------------------------- | ------ | ------------------------- | - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service. | - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +**Error** -- Example +| Error Info | Error Code| Description | +| ------------------------- | ------ | ------------------------- | +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service. | +| Not a directory | 20 | The object specified by the URI is not a directory or album.| + +**Example** ```js - // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.uri - filemanager.listFile(media_path, "file", (err, fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + // Call listFile() and getRoot() to obtain the file path. + let fileInfos = filemanager.getRoot(); + let media_path = ""; + for (let i = 0; i < fileInfos.length; i++) { + if (fileInfos[i].name == "image_album") { + media_path = fileInfos[i].path; + } else if (fileInfos[i].name == "audio_album") { + media_path = fileInfos[i].path; + } else if (fileInfos[i].name == "video_album") { + media_path = fileInfos[i].path; + } else if (fileInfos[i].name == "file_folder") { + media_path = fileInfos[i].path; + } + } + + filemanager.listFile(media_path, "file") + .then((fileInfo) => { + if(Array.isArray(fileInfo)) { + for (var i = 0; i < fileInfo.length; i++) { + console.log("file:"+JSON.stringify(fileInfo)); + } + } + }).catch((err) => { + console.log("Failed to get file"+err); }); ``` @@ -162,34 +187,35 @@ createFile(path : string, filename : string, options? : {dev? : DevInfo}) : P Creates a file in the specified path in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| filename | string | Yes| Name of the file to create.| +| path | string | Yes| URI of the file to create.| +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -- Parameters - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | filename | string | Yes| Name of the file to create.| - | path | string | Yes| URI of the file to create.| - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +**Return value** -- Return value +| Type| Description| +| --- | -- | +| Promise<string> | Promise used to return the URI of the file created.| - | Type| Description| - | --- | -- | - | Promise<string> | Promise used to return the URI of the file created.| +**Error** -- Error - | Error Info| Error Code|Description| - | -- | --- | -- | - | Operation not permitted | 1 | A file with the same name already exists.| - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service.| - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +| Error Info| Error Code|Description| +| -- | --- | -- | +| Operation not permitted | 1 | A file with the same name already exists.| +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service.| +| Not a directory | 20 | The object specified by the URI is not a directory or album.| -- Example +**Example** ```js // Create a file. - let media_path = file.uri // Obtain the file URI using listFile() and getRoot(). + let media_path = "" // Obtain the file URI using listFile() and getRoot(). let name = "xxx.jpg" // File to be saved. filemanager.createFile(media_path, name).then((uri) => { // The URI of the file created is returned. @@ -205,44 +231,50 @@ createFile(path : string, filename: string, options? : {dev? : DevInfo}, callbac Creates a file in the specified path in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------- | ---- | ----------------------------- | - | filename | string | Yes | Name of the file to create. | - | path | string | Yes | URI of the file to create. | - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the file information obtained. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------- | +| filename | string | Yes | Name of the file to create. | +| path | string | Yes | URI of the file to create. | +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | -- Error +**Error** - | Error Info | Error Code| Description | - | ------------------------- | ------ | ------------------------- | - | Operation not permitted | 1 | A file with the same name already exists. | - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service. | - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +| Error Info | Error Code| Description | +| ------------------------- | ------ | ------------------------- | +| Operation not permitted | 1 | A file with the same name already exists. | +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service. | +| Not a directory | 20 | The object specified by the URI is not a directory or album.| -- Example +**Example** ```js // Create a file. // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.uri + let media_path = "" // File to be saved. let name = "xxx.jpg" - filemanager.createFile(media_path, name, (err, uri) => { - // The URI of the file created is returned. - console.log("file uri:"+uri); + let options = { + "dev":{ + "name":"local" + } + }; + filemanager.createFile(media_path, name, options, function(err, uri) { + // The URI of the file created is returned. + console.log("file uri:"+uri); }); + ``` ## FileInfo Defines the file information returned by **getRoot()** or **listFile()**. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService ### Attributes @@ -259,7 +291,7 @@ Defines the file information returned by **getRoot()** or **listFile()**. Defines the device type. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService ### Attributes diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md index b758b2f8e46d2bc4df93d94546f36c0caff4c960..cd6b0eaff6f6f35da2f2899efe36312943ee66d8 100644 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ b/en/application-dev/reference/apis/js-apis-formextension.md @@ -213,7 +213,7 @@ Called when the configuration of the environment where the ability is running is | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | config | [Configuration](#section188911144124715) | Yes| New configuration.| + | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 35a2a3e6a1067c9a9dd26bb8d2ae0e9d39ffcc2e..b66ae2d8b74dd4e1fe13cc917269e88b5d088030 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -99,13 +99,13 @@ Enumerates the key purposes. | Name | Value | Description | | ------------------------ | ---- | -------------------------------- | -| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt plaintext. | -| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt cipher text. | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt plaintext.| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt cipher text.| | HUKS_KEY_PURPOSE_SIGN | 4 | Used to sign data. | | HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signed data. | | HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | -| HUKS_KEY_PURPOSE_WRAP | 32 | Used to wrap data. | -| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for unwrap data. | +| HUKS_KEY_PURPOSE_WRAP | 32 | Used to wrap a key. | +| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used to unwrap a key. | | HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | | HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | @@ -117,14 +117,14 @@ Enumerates the digest algorithms. | Name | Value | Description | | ---------------------- | ---- | ---------------------------------------- | -| HUKS_DIGEST_NONE | 0 | No digest algorithm | -| HUKS_DIGEST_MD5 | 1 | MD5 | -| HUKS_DIGEST_SM39+ | 2 | SM3 | -| HUKS_DIGEST_SHA1 | 10 | SHA1 | -| HUKS_DIGEST_SHA224 | 11 | SHA-224 | -| HUKS_DIGEST_SHA256 | 12 | SHA-256 | -| HUKS_DIGEST_SHA384 | 13 | SHA-384 | -| HUKS_DIGEST_SHA512 | 14 | SHA-512 | +| HUKS_DIGEST_NONE | 0 | No digest algorithm| +| HUKS_DIGEST_MD5 | 1 | MD5| +| HUKS_DIGEST_SM39+ | 2 | SM3| +| HUKS_DIGEST_SHA1 | 10 | SHA1| +| HUKS_DIGEST_SHA224 | 11 | SHA-224| +| HUKS_DIGEST_SHA256 | 12 | SHA-256| +| HUKS_DIGEST_SHA384 | 13 | SHA-384| +| HUKS_DIGEST_SHA512 | 14 | SHA-512| ## HuksKeyPadding @@ -134,11 +134,11 @@ Enumerates the padding algorithms. | Name | Value | Description | | ---------------------- | ---- | ---------------------------------------- | -| HUKS_PADDING_NONE | 0 | No padding algorithm | -| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP) | -| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS) | -| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5 | -| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS) #5 | +| HUKS_PADDING_NONE | 0 | No padding algorithm| +| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| +| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| +| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5| +| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS) #5| | HUKS_PADDING_PKCS7 | 5 | PKCS #7| ## HuksCipherMode @@ -149,12 +149,12 @@ Enumerates the cipher modes. | Name | Value | Description | | ------------- | ---- | --------------------- | -| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode | -| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode | -| HUKS_MODE_CTR | 3 | Counter (CTR) mode | -| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode | -| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode | -| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode | +| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode| +| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| +| HUKS_MODE_CTR | 3 | Counter (CTR) mode| +| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| +| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| +| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| ## HuksKeySize @@ -178,7 +178,7 @@ Enumerates the key sizes. | HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | | HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | | HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | -| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits | +| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| | HUKS_DH_KEY_SIZE_2048 | 2048 | DH key of 2048 bits | | HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | | HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | @@ -201,8 +201,8 @@ Enumerates the key algorithms. | HUKS_ALG_HKDF | 51 | HKDF | | HUKS_ALG_PBKDF2 | 52 | PBKDF2 | | HUKS_ALG_ECDH | 100 | ECDH | -| HUKS_ALG_X25519 | 101 | X25519 | -| HUKS_ALG_ED25519 | 102 | ED25519 | +| HUKS_ALG_X25519 | 101 | X25519 | +| HUKS_ALG_ED25519 | 102 | ED25519| | HUKS_ALG_DH | 103 | DH | | HUKS_ALG_SM29+ | 150 | SM2 | | HUKS_ALG_SM39+ | 151 | SM3 | @@ -228,10 +228,10 @@ Enumerates the key generation modes. | Name | Value | Description | | -------------------------- | ---- | ------------------------------------ | -| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using an API. | -| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using an API. | -| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using a key agreement API. | -| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is derived by using an API. | +| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using an API. | +| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using an API. | +| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using a key agreement API.| +| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is derived by using an API.| ## HuksKeyStorageType @@ -268,7 +268,7 @@ Enumerates the algorithm suites used when a wrapped key is imported. ## HuksImportKeyType9+ -Enumerates the types of the key to import. By default, a public key is imported. This field is not required when a symmetric key is imported. +Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. **System capability**: SystemCapability.Security.Huks @@ -276,7 +276,7 @@ Enumerates the types of the key to import. By default, a public key is imported. | ------------------------- | ---- | ------------------------------ | | HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | | HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | -| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair | +| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| ## HuksTagType @@ -289,8 +289,8 @@ Enumerates the tag data types. | --------------------- | ------- | --------------------------------------- | | HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type | | HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type | -| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type | -| HUKS_TAG_TYPE_ULONG | 3 << 28 | bigint | +| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type| +| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt | | HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean | | HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array | @@ -321,8 +321,8 @@ Enumerates the tags used to invoke parameters. | HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | | HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | | HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | -| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used in key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Alias of the public key during key agreement. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | | HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | | HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | | HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | @@ -342,8 +342,8 @@ Enumerates the tags used to invoke parameters. | HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | | HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | | HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Device brand. | -| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device. | -| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | | HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. | | HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. | | HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. | @@ -352,7 +352,7 @@ Enumerates the tags used to invoke parameters. | HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | | HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. | | HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | -| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used for the attestation. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | | HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | | HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| | HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | @@ -801,12 +801,12 @@ async function TestImportWrappedKeyFunc( await TestExportFunc(wrappingAlias, genOptions); /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. - * For example, import keyA. - * 1. Use ECC to generate a public and private key pair keyB. The public key is keyB_pub, and the private key is keyB_pri. - * 2. Use keyB_pri and the public key obtained from wrappingAlias to negotiate the shared key share_key. - * 3. Randomly generate a key kek for encrypting keyA using AES-GCM. During the encryption, record nonce1/aad1/ciphertext keyA_enc/encrypted tag1. - * 4. Use the share_key to encrypt kek using AES-GCM. During the encryption, record nonce2/aad2/ciphertext kek_enc/encrypted tag2. - * 5. Generate the importOptions.inData field in the following format: + * For example, import **keyA**. + * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. + * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. + * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. + * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, ** aad2**, ciphertext **kek_enc**, and encrypted **tag2**. + * 5. Generate the **importOptions.inData** field in the following format: * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index dc9f7442dab9fd1b39f12cf3fff71bfd83c13551..5c45f18dc00dba05a5615311c968f342cd6684d3 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,9 +1,9 @@ -# Internationalization – i18n +# Internationalization – I18N > **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. > -> - This module contains enhanced i18n APIs, which are not defined in ECMA 402. +> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md). ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index ff9c8b14b4aba73b734f9fb61f4e6f2d1d2755aa..85ff0550112bbfc81e22925c3a69ca7ac813cfab 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -34,6 +34,7 @@ Creates a **PixelMap** object. This API uses a promise to return the result. ```js const color = new ArrayBuffer(96); +let bufferArr = new Unit8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts) .then((pixelmap) => { @@ -60,6 +61,7 @@ Creates a **PixelMap** object. This API uses an asynchronous callback to return ```js const color = new ArrayBuffer(96); +let bufferArr = new Unit8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (pixelmap) => { }) @@ -100,10 +102,11 @@ Reads image pixel map data and writes the data to an **ArrayBuffer**. This API u **Example** ```js -pixelmap.readPixelsToBuffer(ReadBuffer).then(() => { - console.log('readPixelsToBuffer succeeded.'); // Called if the condition is met. +const readBuffer = new ArrayBuffer(400); +pixelmap.readPixelsToBuffer(readBuffer).then(() => { + console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. }).catch(error => { - console.log('readPixelsToBuffer failed.'); // Called if no condition is met. + ('Failed to read image pixel data.'); // Called if no condition is met. }) ``` @@ -125,11 +128,12 @@ Reads image pixel map data and writes the data to an **ArrayBuffer**. This API u **Example** ```js -pixelmap.readPixelsToBuffer(ReadBuffer, (err, res) => { +const readBuffer = new ArrayBuffer(400); +pixelmap.readPixelsToBuffer(readBuffer, (err, res) => { if(err) { - console.log('readPixelsToBuffer failed.'); // Called if the condition is met. + console.log('Failed to read image pixel data.'); // Called if no condition is met. } else { - console.log('readPixelsToBuffer succeeded.'); // Called if the condition is met. + console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. } }) ``` @@ -157,10 +161,11 @@ Reads image pixel map data in an area. This API uses a promise to return the dat **Example** ```js -pixelmap.readPixels(Area).then((data) => { - console.log('readPixels succeeded.'); // Called if the condition is met. +const area = new ArrayBuffer(400); +pixelmap.readPixels(area).then(() => { + console.log('Succeeded in reading the image data in the area.'); // Called if the condition is met. }).catch(error => { - console.log('readPixels failed.'); // Called if no condition is met. + console.log('Failed to read the image data in the area.'); // Called if no condition is met. }) ``` @@ -182,6 +187,8 @@ Reads image pixel map data in an area. This API uses an asynchronous callback to **Example** ```js +const color = new ArrayBuffer(96); +let bufferArr = new Unit8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (err, pixelmap) => { if(pixelmap == undefined){ @@ -222,6 +229,7 @@ Writes image pixel map data to an area. This API uses a promise to return the op ```js const color = new ArrayBuffer(96); +let bufferArr = new Unit8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts) .then( pixelmap => { @@ -233,7 +241,7 @@ image.createPixelMap(color, opts) stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 } } - var bufferArr = new Uint8Array(area.pixels); + let bufferArr = new Uint8Array(area.pixels); for (var i = 0; i < bufferArr.length; i++) { bufferArr[i] = i + 1; } @@ -269,13 +277,18 @@ Writes image pixel map data to an area. This API uses an asynchronous callback t **Example** ```js -pixelmap.writePixels(Area, () => { - const readArea = { - pixels: new ArrayBuffer(20), - offset: 0, - stride: 8, - region: { size: { height: 1, width: 2 }, x: 0, y: 0 }, - } +const area = new ArrayBuffer(400); +pixelmap.writePixels(area, (error) => { + if (error!=undefined) { + console.info('Failed to write pixelmap into the specified area.'); + } else { + const readArea = { + pixels: new ArrayBuffer(20), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 }, + } + } }) ``` @@ -302,7 +315,10 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj **Example** ```js -PixelMap.writeBufferToPixels(color).then(() => { +const color = new ArrayBuffer(96); +const pixelMap = new ArrayBuffer(400); +let bufferArr = new Unit8Array(color); +pixelMap.writeBufferToPixels(color).then(() => { console.log("Succeeded in writing data from a buffer to a PixelMap."); }).catch((err) => { console.error("Failed to write data from a buffer to a PixelMap."); @@ -327,7 +343,10 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj **Example** ```js -PixelMap.writeBufferToPixels(color, function(err) { +const color = new ArrayBuffer(96);\ +const pixelMap = new ArrayBuffer(400); +let bufferArr = new Unit8Array(color); +pixelMap.writeBufferToPixels(color, function(err) { if (err) { console.error("Failed to write data from a buffer to a PixelMap."); return; @@ -354,7 +373,8 @@ Obtains pixel map information of this image. This API uses a promise to return t **Example** ```js -PixelMap.getImageInfo().then(function(info) { +const pixelMap = new ArrayBuffer(400); +pixelMap.getImageInfo().then(function(info) { console.log("Succeeded in obtaining the image pixel map information."); }).catch((err) => { console.error("Failed to obtain the image pixel map information."); @@ -379,9 +399,7 @@ Obtains pixel map information of this image. This API uses an asynchronous callb ```js pixelmap.getImageInfo((imageInfo) => { - console.log("getImageInfo succeeded."); -}).catch((err) => { - console.error("getImageInfo failed."); + console.log("Succeeded in obtaining the image pixel map information.."); }) ``` @@ -402,7 +420,10 @@ Obtains the number of bytes per line of the image pixel map. **Example** ```js -image.createPixelMap(clolr, opts, (err,pixelmap) => { +const color = new ArrayBuffer(96); +let bufferArr = new Unit8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err,pixelmap) => { let rowCount = pixelmap.getBytesNumberPerRow(); }) ``` @@ -444,11 +465,14 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js +const color = new ArrayBuffer(96); +let bufferArr = new Unit8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (pixelmap) => { pixelmap.release().then(() => { - console.log('release succeeded.'); + console.log('Succeeded in releasing pixelmap object.'); }).catch(error => { - console.log('release failed.'); + console.log('Failed to release pixelmap object.'); }) }) ``` @@ -470,11 +494,14 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Example** ```js +const color = new ArrayBuffer(96); +let bufferArr = new Unit8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (pixelmap) => { pixelmap.release().then(() => { - console.log('release succeeded.'); + console.log('Succeeded in releasing pixelmap object.'); }).catch(error => { - console.log('release failed.'); + console.log('Failed to release pixelmap object.'); }) }) ``` @@ -589,9 +616,7 @@ Obtains information about this image. This API uses an asynchronous callback to ```js imageSourceApi.getImageInfo(imageInfo => { - console.log('getImageInfo succeeded.'); -}).catch(error => { - console.log('getImageInfo failed.'); + console.log('Succeeded in obtaining the image information.'); }) ``` @@ -620,9 +645,9 @@ Obtains information about an image with the specified index. This API uses a pro ```js imageSourceApi.getImageInfo(0) .then(imageInfo => { - console.log('getImageInfo succeeded.'); + console.log('Succeeded in obtaining the image information.'); }).catch(error => { - console.log('getImageInfo failed.'); + console.log('Failed to obtain the image information.'); }) ``` @@ -652,9 +677,7 @@ Obtains the value of a property with the specified index in this image. This API ```js imageSourceApi.getImageProperty("BitsPerSample") .then(data => { - console.log('getImageProperty succeeded.'); - }).catch(error => { - console.log('getImageProperty failed.'); + console.log('Succeeded in getting the value of the specified attribute key of the image.'); }) ``` @@ -678,9 +701,9 @@ Obtains the value of a property with the specified index in this image. This API ```js imageSourceApi.getImageProperty("BitsPerSample",(error,data) => { if(error) { - console.log('getImageProperty failed.'); + console.log('Failed to get the value of the specified attribute key of the image.'); } else { - console.log('getImageProperty succeeded.'); + console.log('Succeeded in getting the value of the specified attribute key of the image.'); } }) ``` @@ -704,11 +727,12 @@ Obtains the value of a property in this image. This API uses an asynchronous cal **Example** ```js -imageSourceApi.getImageProperty("BitsPerSample",Property,(error,data) => { +const property = new ArrayBuffer(400); +imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => { if(error) { - console.log('getImageProperty failed.'); + console.log('Failed to get the value of the specified attribute key of the image.'); } else { - console.log('getImageProperty succeeded.'); + console.log('Succeeded in getting the value of the specified attribute key of the image.'); } }) ``` @@ -737,9 +761,9 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses ```js imageSourceApi.createPixelMap().then(pixelmap => { - console.log('createPixelMap succeeded.'); + console.log('Succeeded in creating pixelmap object through image decoding parameters.'); }).catch(error => { - console.log('createPixelMap failed.'); + console.log('Failed to create pixelmap object through image decoding parameters.'); }) ``` @@ -761,9 +785,9 @@ Creates a **PixelMap** object based on the default parameters. This API uses an ```js imageSourceApi.createPixelMap(pixelmap => { - console.log('createPixelMap succeeded.'); + console.log('Succeeded in creating pixelmap object.'); }).catch(error => { - console.log('createPixelMap failed.'); + console.log('Failed to create pixelmap object.'); }) ``` @@ -785,11 +809,10 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Example** ```js +const decodingOptions = new ArrayBuffer(400); imageSourceApi.createPixelMap(decodingOptions, pixelmap => { - console.log('createPixelMap succeeded.'); -}).catch(error => { - console.log('createPixelMap failed.'); -}) + console.log('Succeeded in creating pixelmap object.'); +}) ``` ### release @@ -811,8 +834,6 @@ Releases this **ImageSource** instance. This API uses an asynchronous callback t ```js imageSourceApi.release(() => { console.log('release succeeded.'); -}).catch(error => { - console.log('release failed.'); }) ``` @@ -834,9 +855,9 @@ Releases this **ImageSource** instance. This API uses a promise to return the re ```js imageSourceApi.release().then(()=>{ - console.log('release succeeded.'); + console.log('Succeeded in releasing the image source instance.'); }).catch(error => { - console.log('release failed.'); + console.log('Failed to release the image source instance.'); }) ``` @@ -891,8 +912,9 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:["image/jpeg"], quality:98 }; -imagePackerApi.packing(ImageSourceApi, packOpts, data => {}) +let packOpts = { format:"image/jpeg", quality:98 }; +const imageSourceApi = new ArrayBuffer(400); +imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` ### packing @@ -919,8 +941,9 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:["image/jpeg"], quality:98 } -imagePackerApi.packing(ImageSourceApi, packOpts) +let packOpts = { format:"image/jpeg", quality:98 } +const imageSourceApi = new ArrayBuffer(400); +imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { console.log('packing succeeded.'); }).catch(error => { @@ -947,11 +970,12 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:["image/jpeg"], quality:98 } -imagePackerApi.packing(PixelMapApi, packOpts, data => { - console.log('packing succeeded.'); +let packOpts = { format:"image/jpeg", quality:98 } +const pixelMapApi = new ArrayBuffer(400); +imagePackerApi.packing(pixelMapApi, packOpts, data => { + console.log('Succeeded in packing the image.'); }).catch(error => { - console.log('packing failed.'); + console.log('Failed to pack the image.'); }) ``` @@ -979,12 +1003,13 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:["image/jpeg"], quality:98 } -imagePackerApi.packing(PixelMapApi, packOpts) +let packOpts = { format:"image/jpeg", quality:98 } +const pixelMapApi = new ArrayBuffer(400); +imagePackerApi.packing(pixelMapApi, packOpts) .then( data => { - console.log('packing succeeded.'); + console.log('Succeeded in packing the image.'); }).catch(error => { - console.log('packing failed.'); + console.log('Failed to pack the image..'); }) ``` @@ -1006,9 +1031,7 @@ Releases this **ImagePacker** instance. This API uses an asynchronous callback t ```js imagePackerApi.release(()=>{ - console.log('release succeeded.'); -}).catch(error => { - console.log('release failed.'); + console.log('Succeeded in releasing image packaging.'); }) ``` @@ -1030,9 +1053,9 @@ Releases this **ImagePacker** instance. This API uses a promise to return the re ```js imagePackerApi.release().then(()=>{ - console.log('release succeeded.'); + console.log('Succeeded in releasing image packaging.'); }).catch((error)=>{ - console.log('release failed.'); + console.log('Failed to release image packaging.'); }) ``` @@ -1098,7 +1121,7 @@ Obtains a surface ID for the camera or other components. This API uses an asynch **Example** ```js - receiver.getReceivingSurfaceId((err, id) => { +receiver.getReceivingSurfaceId((err, id) => { if(err) { console.log('getReceivingSurfaceId failed.'); } else { @@ -1513,7 +1536,7 @@ Defines image decoding options. | desiredSize | [Size](#size) | Yes | Yes | Expected output size. | | desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| -| index | number | Yes | Yes | Index of the image to decode. | +| index | number | Yes | Yes | Index of the image to decode. | ## Region7+ @@ -1536,7 +1559,7 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | -------------- | | format | string | Yes | Yes | Format of the packed image. | -| quality | number | Yes | Yes | Quality of the packed image.| +| quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| ## GetImagePropertyOptions7+ diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index 8a458433505279ac0bd72b1d418972b409bd59f9..dbb47a0d3ad9ee20ee500bc1d51d61ff380f63a5 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,5 +1,6 @@ -# Combination Key +# Input Consumer +The Input Consumer module implements listening for key events. > **NOTE**
> @@ -18,19 +19,21 @@ import inputConsumer from '@ohos.multimodalInput.inputConsumer'; ## inputConsumer.on -on(type: "key", keyOptions: KeyOptions, callback: Callback): void +on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): void Enables listening for combination key events. When a combination key event that meets the specified conditions occurs, **keyOptions** will be passed as an input parameter to **callback**. +This is a system API. + **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| -| keyOptions | [keyOptions](#keyOptions) | Yes| Key option, which specifies the condition for combination key input.| -| callback | KeyOptions | Yes| Callback used to return the result.
When a key input event that meets the specified options occurs, **keyOptions** will be passed as an input parameter to **callback**.| +| type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| +| keyOptions | [keyOptions](#keyOptions) | Yes| Key option, which specifies the condition for combination key input.| +| callback | Callback<KeyOptions> | Yes| Callback used to return the result.
When a key input event that meets the specified options occurs, **keyOptions** will be passed as an input parameter to **callback**.| **Example** @@ -46,10 +49,12 @@ inputConsumer.on('key', keyOptions, callback); ## inputConsumer.off -off(type: "key", keyOptions: KeyOptions, callback?: Callback): void +off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): void Stops listening for combination key events. +This is a system API. + **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer **Parameters** @@ -58,7 +63,7 @@ Stops listening for combination key events. | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| | keyOptions | [keyOptions](#keyOptions) | Yes| Key options passed to the key input event when listening starts.| -| callback | Callback | Yes| Callback function passed to the key input event with **keyOptions** when listening starts.| +| callback | Callback<KeyOptions> | Yes| Callback function passed to the key input event with **keyOptions** when listening starts.| **Example** @@ -76,6 +81,8 @@ inputConsumer.off('key', keyOptions, callback); Defines the key options that are met when a combination key input event occurs. +This is a system API. + **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index c47a977b1f2b1559488b6f6602a6ed116ad88197..c1ec2c787a6f9e47c1c87715b5ea52171dbac85f 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -1,7 +1,7 @@ # Input Device -The input device management module is used to listen for the connection, disconnection, and updates of input devices and display 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. +The Input Device 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**
@@ -179,7 +179,7 @@ inputDevice.getDevice(1).then((inputDevice)=>{ ## inputDevice.supportKeys9+ -supportKeys(deviceId: number, keys: Array<KeyCode>, callback: Callback<Array<boolean>>): void; +supportKeys(deviceId: number, keys: Array<KeyCode>, callback: Callback<Array<boolean>>): void Obtains the key codes supported by the input device. This API uses an asynchronous callback to return the result. @@ -204,7 +204,7 @@ inputDevice.supportKeys(1, [17, 22, 2055], (ret)=>{ ## inputDevice.supportKeys9+ -supportKeys(deviceId: number, keys: Array<KeyCode>): Promise<Array<boolean>>; +supportKeys(deviceId: number, keys: Array<KeyCode>): Promise<Array<boolean>> Obtains the key codes supported by the input device. This API uses a promise to return the result. @@ -234,7 +234,7 @@ inputDevice.supportKeys(1, [17, 22, 2055]).then((ret)=>{ ## inputDevice.getKeyboardType9+ -getKeyboardType(deviceId: number, callback: AsyncCallback<KeyboardType>): void; +getKeyboardType(deviceId: number, callback: AsyncCallback<KeyboardType>): void Obtains the keyboard type of an input device. This API uses an asynchronous callback to return the result. @@ -258,7 +258,7 @@ inputDevice.getKeyboardType(1, (ret)=>{ ## inputDevice.getKeyboardType9+ -getKeyboardType(deviceId: number,): Promise<KeyboardType>; +getKeyboardType(deviceId: number,): Promise<KeyboardType> Obtains the keyboard type of an input device. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md index 5718f96c2c75a8950af27d7de8e9ad40866d4198..862c39c608ba76b56c23b675c9ef1da19c43331f 100644 --- a/en/application-dev/reference/apis/js-apis-inputevent.md +++ b/en/application-dev/reference/apis/js-apis-inputevent.md @@ -1,5 +1,7 @@ # Input Event +The Input Event module describes basic events reported by an input device. + > **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. @@ -9,6 +11,8 @@ import InputEvent from '@ohos.multimodalInput.inputEvent'; ``` +## InputEvent + **System capability**: SystemCapability.MultimodalInput.Input.Core **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index be8c4ad17b0963d9761194eb009580ef37347e31..c38734f143bed4fd8288df7672d721caf4696025 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,11 +1,12 @@ # Key Injection +The Key Injection module implements injection of key events. > **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. +> - 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. > -> The APIs of this module are system APIs and cannot be called by third-party applications. +> - The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -22,6 +23,8 @@ injectEvent({KeyEvent: KeyEvent}): void Injects a key event. +This is a system API. + **System capability**: SystemCapability.MultimodalInput.Input.InputSimulator **Parameters** @@ -54,6 +57,6 @@ Defines the information about the key event to inject. | Name | Type | Mandatory | Description | | --------------- | ------- | ---- | --------- | | isPressed | boolean | Yes | Whether the key is pressed. | -| keyCode | Number | Yes | Key code. | -| keyDownDuration | boolean | Yes | Duration within which the key is pressed. | -| isIntercepted | Number | Yes | Whether the key can be intercepted.| +| keyCode | number | Yes | Key code. | +| keyDownDuration | number | Yes | Duration within which the key is pressed. | +| isIntercepted | boolean | Yes | Whether the key can be intercepted.| diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 6bbd043fd8eefaf4809c123e0b3fb465b9d59722..07084623fbe78c307fdc787b1715b398e3d97675 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,5 +1,6 @@ # Input Monitor +The Input Monitor module implements listening for global touch events. > **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. @@ -26,6 +27,8 @@ on(type: "touch", receiver: TouchEventReceiver): void Enables listening for global touch events. +This is a system API. + **Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor @@ -46,10 +49,12 @@ inputMonitor.off("touch", (event) => { }); ``` -on(type: "mouse", receiver:Callback):void +on(type: "mouse", receiver: Callback<MouseEvent>): void Enables listening for global mouse events. +This is a system API. + **Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor @@ -59,7 +64,7 @@ Enables listening for global mouse events. | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------- | | type | string | Yes | Type of the input event to listen for. The value is **mouse**.| -| receiver | Callback | Yes | Callback used to return the mouse event. | +| receiver | Callback<MouseEvent> | Yes | Callback used to return the mouse event. | **Example** @@ -73,10 +78,12 @@ inputMonitor.off("mouse", (event) => { ## inputMonitor.off -off(type: "touch", receiver?:TouchEventReceiver):void +off(type: "touch", receiver?: TouchEventReceiver): void Stops listening for global touch events. +This is a system API. + **Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor @@ -98,6 +105,8 @@ off(type: "mouse", receiver?:Callback):void Stops listening for global mouse events. +This is a system API. + **Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor @@ -107,7 +116,7 @@ Stops listening for global mouse events. | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------- | | type | string | Yes | Type of the input event to listen for. The value is **mouse**.| -| receiver | Callback | No | Callback used to return the mouse event. | +| receiver | Callback<MouseEvent> | No | Callback used to return the mouse event. | **Example** @@ -119,12 +128,9 @@ inputMonitor.off("mouse"); ## TouchEventReceiver -This class provides the callback of touch events. - - -### (touchEvent: TouchEvent): Boolean +Provides the callback of touch events. -Represents the callback used to return the touch event. You need to define the name of the callback function in the correct format. Ensure that the input parameter is of the **TouchEvent** type, and the return value is of the **Boolean** type. +This is a system API. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 2ae9a62bcd2d4a436cfdef61c31383ed929b09b6..d9be9b9a2cbc59fb48e2beae81da77d05be9c84f 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,10 +1,9 @@ -# Internationalization – intl +# Internationalization – Intl > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - This module contains standard i18n APIs, which are defined in ECMA 402. - +> - This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402. For details about the enhanced I18N capabilities, see [I18N](js-apis-i18n.md). ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index 5bf402c3d736c674c767a915147f2a43c850c23b..9a1c1712577e7d34c841ba19fc47376166ad231c 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -1,6 +1,6 @@ # Keycode -Provides keycodes for a key device. +The Keycode module provides keycodes for a key device. > **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. @@ -11,6 +11,8 @@ Provides keycodes for a key device. import {KeyCode} from '@ohos.multimodalInput.keyCode' ``` +## KeyCode + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name| Type| Readable| Writable| Description| diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index 085bee426f36b96e2538ab4ad8f13cf5086b5b9c..ded0aab53e599fd8aebad2de8963fc503e83d8fb 100644 --- a/en/application-dev/reference/apis/js-apis-keyevent.md +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -1,6 +1,6 @@ # Key Event -Represents key events reported by an input device. +The Key Event module provides key events reported by an input device. > **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. diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 49f6e8f5ab16a3f6f28980204181f54a4e22c992..77002020139fbdb2aada0cb1141a0f2840a9f250 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -274,7 +274,7 @@ For details about the audio playback demo, see [Audio Playback Development](../. | Name | Type | Readable| Writable| Description | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| +| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HTTPS network playback: https://xx
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | currentTime | number | Yes | No | Current audio playback position. | | duration | number | Yes | No | Audio duration. | @@ -501,7 +501,7 @@ Subscribes to the audio buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | | callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** @@ -525,7 +525,7 @@ Subscribes to the audio playback events. | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'
- The 'play' event is triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- The 'pause' event is triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- The 'stop' event is triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- The 'reset' event is triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- The 'finish' event is triggered when the audio playback is finished.
- The 'volumeChange' event is triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed.| +| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed. | | callback | () => void | Yes | Callback invoked when the event is triggered. | **Example** @@ -598,7 +598,7 @@ Subscribes to the 'timeUpdate' event. | Name | Type | Mandatory| Description | | -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'timeUpdate' in this API.
The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) API is called.| +| type | string | Yes | Event type, which is 'timeUpdate' in this case.
The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) API is called.| | callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful. | **Example** @@ -626,7 +626,7 @@ Subscribes to the audio playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during audio playback.| +| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during audio playback.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -656,7 +656,7 @@ Enumerates the audio playback states. You can obtain the state through the **sta ## VideoPlayer8+ -Provides APIs to manage and play video. Before calling an API of the **VideoPlayer** class, you must call [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. +Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must call [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). @@ -666,7 +666,7 @@ For details about the video playback demo, see [Video Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| +| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HTTPS network playback: https://xx
3. HLS network playback: http://xx or https://xx
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | currentTime8+ | number | Yes | No | Current video playback position. | | duration8+ | number | Yes | No | Video duration. The value **-1** indicates the live streaming mode. | @@ -1003,7 +1003,8 @@ Seeks to the specified playback position. The next key frame at the specified po **Example** ```js -videoPlayer.seek((seekTime, err) => { +let seekTime = 5000; +videoPlayer.seek(seekTime, (err, result) => { if (typeof (err) == 'undefined') { console.info('seek success!'); } else { @@ -1031,7 +1032,10 @@ Seeks to the specified playback position. This API uses a callback to return the **Example** ```js -videoPlayer.seek((seekTime, seekMode, err) => { +import media from '@ohos.multimedia.media' +let seekTime = 5000; +let seekMode = media.SeekMode.SEEK_NEXT_SYNC; +videoPlayer.seek(seekTime, seekMode, (err, result) => { if (typeof (err) == 'undefined') { console.info('seek success!'); } else { @@ -1064,6 +1068,7 @@ Seeks to the specified playback position. If **mode** is not specified, the next **Example** ```js +let seekTime = 5000; videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. console.info('seek success'); }).catch((error) => { @@ -1095,7 +1100,8 @@ Sets the volume. This API uses a callback to return the result. **Example** ```js -videoPlayer.setVolume((vol, err) => { +let vol = 0.5; +videoPlayer.setVolume(vol, (err, result) => { if (typeof (err) == 'undefined') { console.info('setVolume success!'); } else { @@ -1127,6 +1133,7 @@ Sets the volume. This API uses a promise to return the result. **Example** ```js +let vol = 0.5; videoPlayer.setVolume(vol).then() => { console.info('setVolume success'); }).catch((error) => { @@ -1278,7 +1285,10 @@ Sets the video playback speed. This API uses a callback to return the result. **Example** ```js -videoPlayer.setSpeed((speed:number, err) => { +import media from '@ohos.multimedia.media' +let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; + +videoPlayer.setSpeed(speed, (err, result) => { if (typeof (err) == 'undefined') { console.info('setSpeed success!'); } else { @@ -1310,6 +1320,9 @@ Sets the video playback speed. This API uses a promise to return the result. **Example** ```js +import media from '@ohos.multimedia.media' +let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; + videoPlayer.setSpeed(speed).then() => { console.info('setSpeed success'); }).catch((error) => { @@ -1317,6 +1330,65 @@ videoPlayer.setSpeed(speed).then() => { }); ``` +### selectBitrate9+ + +selectBitrate(bitrate:number, callback: AsyncCallback\): void + +Selects a bit rate from available bit rates. This API uses a callback to return the result. The available bit rates can be obtained by calling [availableBitrateCollected](#on('availableBitrateCollected')9+). + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------------------------------------------- | +| bitrate | number | Yes | Bit rate to select, which is used in the HLS multi-bit rate scenario. The unit is bit/s. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the set value is returned, the operation is successful; otherwise, the operation fails.| + +**Example** + +```js +let bitrate = 1024000; +videoPlayer.selectBitrate(bitrate, (err, result) => { + if (typeof (err) == 'undefined') { + console.info('selectBitrate success!'); + } else { + console.info('selectBitrate fail!'); + } +}); +``` + +### selectBitrate9+ + +selectBitrate(bitrate:number): Promise\ + +Selects a bit rate from available bit rates. This API uses a promise to return the result. The available bit rates can be obtained by calling [availableBitrateCollected](#on('availableBitrateCollected')9+). + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------------------- | +| bitrate | number | Yes | Bit rate to select, which is used in the HLS multi-bit rate scenario. The unit is bit/s.| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let bitrate = 1024000; +videoPlayer.selectBitrate(bitrate).then() => { + console.info('selectBitrate success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error.message}`); +}); +``` + ### on('playbackCompleted')8+ on(type: 'playbackCompleted', callback: Callback\): void @@ -1329,7 +1401,7 @@ Subscribes to the video playback completion event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ----------------------------------------------------------- | -| type | string | Yes | Type of the event to subscribe to, which is 'playbackCompleted' in this example.| +| type | string | Yes | Event type, which is 'playbackCompleted' in this case.| | callback | function | Yes | Callback invoked when the event is triggered. | **Example** @@ -1352,7 +1424,7 @@ Subscribes to the video buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | | callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** @@ -1376,7 +1448,7 @@ Subscribes to the frame rendering start event. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'startRenderFrame' in this example.| +| type | string | Yes | Event type, which is 'startRenderFrame' in this case.| | callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** @@ -1399,7 +1471,7 @@ Subscribes to the video width and height change event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'videoSizeChanged' in this example.| +| type | string | Yes | Event type, which is 'videoSizeChanged' in this case.| | callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | **Example** @@ -1423,7 +1495,7 @@ Subscribes to the video playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during video playback.| +| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during video playback.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -1437,6 +1509,31 @@ videoPlayer.on('error', (error) => { // Set the 'error' event callback. videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` +### on('availableBitrateCollected')9+ + +on(type: 'availableBitrateCollected', callback: (bitrates: Array) => void): void + +Subscribes to the video playback bit rate reporting event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is 'availableBitrateCollected' in this case. This event is reported only once when the playback starts.| +| callback | function | Yes | Callback used to return supported bit rates, in an array. | + +**Example** + +```js +videoPlayer.on('availableBitrateCollected', (bitrates) => { + for (let i = 0; i < bitrates.length; i++) { + console.info('case availableBitrateCollected bitrates: ' + bitrates[i]); // Print bit rates. + } +}); +``` + ## VideoPlayState8+ Enumerates the video playback states. You can obtain the state through the **state** attribute. @@ -1512,7 +1609,7 @@ audioPlayer.getTrackDescription((error, arrlist) => { ## AudioRecorder -Implements audio recording. Before calling an API of the **AudioRecorder** class, you must call [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. +Implements audio recording. Before calling an API of **AudioRecorder**, you must call [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). @@ -1530,7 +1627,7 @@ Prepares for recording. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, [encoding format](#audioencoder), sampling rate, number of audio channels, and [output format](#audiooutputformat).| +| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.| **Example** @@ -1668,7 +1765,7 @@ Subscribes to the audio recording events. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\| 'pause' \| 'resume' \|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- The 'start' event is triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- The 'pause' event is triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- The 'resume' event is triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- The 'stop' event is triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- The 'release' event is triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- The 'reset' event is triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset.| +| type | string | Yes | Event type. The following events are supported: 'prepare'\|'start'\| 'pause' \| 'resume' \|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- The 'start' event is triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- The 'pause' event is triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- The 'resume' event is triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- The 'stop' event is triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- The 'release' event is triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- The 'reset' event is triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset.| | callback | ()=>void | Yes | Callback invoked when the event is triggered. | **Example** @@ -1726,7 +1823,7 @@ Subscribes to the audio recording error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during audio recording.| +| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during audio recording.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -1748,15 +1845,15 @@ Describes audio recording configurations. | Name | Type | Mandatory| Description | | --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**. | +| audioEncoder(deprecated) | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**.
**Note**: This parameter is deprecated since API version 8. Use **audioEncoderMime** instead. | | audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**. | | audioSampleRate | number | No | Audio sampling rate. The default value is **48000**. | | numberOfChannels | number | No | Number of audio channels. The default value is **2**. | -| format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | +| format(deprecated) | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**.
**Note**: This parameter is deprecated since API version 8. Use **fileFormat** instead. | | location | [Location](#location) | No | Geographical location of the recorded audio. | -| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| -| audioEncoderMime | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | - +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| audioEncoderMime8+ | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | +| fileFormat8+ | [ContainerFormatType](#containerformattype8) | No | Audio encoding format. | ## AudioEncoder(deprecated) @@ -1773,13 +1870,13 @@ Enumerates the audio encoding formats. | AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| | AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| | AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| ## AudioOutputFormat(deprecated) > **NOTE** -> This API is deprecated since API version 8. You are advised to use [ContainerFormatType ](#containerformattype8) instead. +> This API is deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead. Enumerates the audio output formats. @@ -1805,7 +1902,7 @@ For details about the video recording demo, see [Video Recording Development](.. | Name | Type | Readable| Writable| Description | | ------------------ | -------------------------------------- | ---- | ---- | ---------------- | -| state8+ | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.| +| state9+ | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.| ### prepare9+ @@ -2346,7 +2443,7 @@ Subscribes to the video recording error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during video recording.| +| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during video recording.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -2388,7 +2485,7 @@ Describes the video recording parameters. | profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | | rotation | number | No | Rotation angle of the recorded video. | | location | [Location](#location) | No | Geographical location of the recorded video. | -| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| ## AudioSourceType9+ diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index bb62764d00730e1abb51a3b302915cd6bee264ca..e1dbb5f4a54b3936dc4b52e76ab5ad0fc0a39265 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,6 +1,8 @@ # OS Account Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+The osAccount module provides basic capabilities for managing operating system (OS) accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account, and storing OS account data to disks. + +> **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. @@ -18,7 +20,7 @@ Obtains an **AccountManager** instance. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | --------------------------------- | ------------------------ | | [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.| @@ -76,7 +78,7 @@ This is a system API and cannot be called by third-party applications. activateOsAccount(localId: number): Promise<void> -Activates an OS account. This API uses a promise to return the result asynchronously. +Activates an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -90,7 +92,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the OS account to activate.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -135,11 +137,11 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous isMultiOsAccountEnable(): Promise<boolean> -Checks whether multiple OS accounts are supported. This API uses a promise to return the result asynchronously. +Checks whether multiple OS accounts are supported. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -188,7 +190,7 @@ Checks whether an OS account is activated. This API uses an asynchronous callbac isOsAccountActived(localId: number): Promise<boolean> -Checks whether an OS account is activated. This API uses a promise to return the result asynchronously. +Checks whether an OS account is activated. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -200,7 +202,7 @@ Checks whether an OS account is activated. This API uses a promise to return the | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -251,7 +253,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boolean> -Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result asynchronously. +Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -264,7 +266,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | localId | number | Yes | ID of the target OS account. | | constraint | string | Yes | [Constraint](#constraints) specified.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -310,11 +312,11 @@ Checks whether this OS account is a test account. This API uses an asynchronous isTestOsAccount(): Promise<boolean> -Checks whether this OS account is a test account. This API uses a promise to return the result asynchronously. +Checks whether this OS account is a test account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -386,7 +388,7 @@ Checks whether an OS account has been verified. This API uses an asynchronous ca isOsAccountVerified(localId?: number): Promise<boolean> -Checks whether an OS account has been verified. This API uses a promise to return the result asynchronously. +Checks whether an OS account has been verified. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -398,7 +400,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur | ------- | ------ | ---- | ------------------ | | localId | number | No | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -451,7 +453,7 @@ This is a system API and cannot be called by third-party applications. removeOsAccount(localId: number): Promise<void> -Removes an OS account. This API uses a promise to return the result asynchronously. +Removes an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -465,7 +467,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the OS account to remove.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -522,7 +524,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean): Promise<void> -Sets or removes constraints for an OS account. This API uses a promise to return the result asynchronously. +Sets or removes constraints for an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -538,7 +540,7 @@ This is a system API and cannot be called by third-party applications. | constraints | Array<string> | Yes | List of [constraints](#constraints) to set or remove.| | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -591,7 +593,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountName(localId: number, localName: string): Promise<void> -Sets a name for an OS account. This API uses a promise to return the result asynchronously. +Sets a name for an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -606,7 +608,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | localName | string | Yes | Account name to set. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -655,13 +657,13 @@ Obtains the number of OS accounts created. This API uses an asynchronous callbac getCreatedOsAccountsCount(): Promise<number> -Obtains the number of OS accounts created. This API uses a promise to return the result asynchronously. +Obtains the number of OS accounts created. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -706,11 +708,11 @@ Obtains the ID of the OS account to which the current process belongs. This API getOsAccountLocalIdFromProcess(): Promise<number> -Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. +Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -757,7 +759,7 @@ Obtains the OS account ID based on the process UID. This API uses an asynchronou getOsAccountLocalIdFromUid(uid: number): Promise<number> -Obtains the OS account ID based on the process UID. This API uses a promise to return the result asynchronously. +Obtains the OS account ID based on the process UID. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -767,7 +769,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r | ------ | ------ | ---- | --------- | | uid | number | Yes | Process UID.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -817,7 +819,7 @@ Obtains the OS account ID based on domain account information. This API uses an getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> -Obtains the OS account ID based on domain account information. This API uses a promise to return the result asynchronously. +Obtains the OS account ID based on domain account information. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -829,7 +831,7 @@ Obtains the OS account ID based on domain account information. This API uses a p | ---------- | --------------------------------------- | ---- | ------------ | | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -877,13 +879,13 @@ This is a system API and cannot be called by third-party applications. queryMaxOsAccountNumber(): Promise<number> -Obtains the maximum number of OS accounts that can be created. This API uses a promise to return the result asynchronously. +Obtains the maximum number of OS accounts that can be created. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -932,7 +934,7 @@ Obtains all constraints enabled for an OS account. This API uses an asynchronous getOsAccountAllConstraints(localId: number): Promise<Array<string>> -Obtains all constraints enabled for an OS account. This API uses a promise to return the result asynchronously. +Obtains all constraints enabled for an OS account. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -944,7 +946,7 @@ Obtains all constraints enabled for an OS account. This API uses a promise to re | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------- | :----------------------------------------------------------- | @@ -972,6 +974,8 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + **Parameters** | Name | Type | Mandatory| Description | @@ -992,13 +996,15 @@ This is a system API and cannot be called by third-party applications. queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> -Obtains information about all the OS accounts created. This API uses a promise to return the result asynchronously. +Obtains information about all the OS accounts created. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**Return value** | Type | Description | | :---------------------------------------------------------- | :----------------------------------------------------------- | @@ -1046,11 +1052,11 @@ Obtains information about all activated OS accounts. This API uses an asynchrono queryActivatedOsAccountIds(): Promise<Array<number>> -Obtains information about all activated OS accounts. This API uses a promise to return the result asynchronously. +Obtains information about all activated OS accounts. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------- | :----------------------------------------------------------- | @@ -1101,7 +1107,7 @@ This is a system API and cannot be called by third-party applications. createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInfo> -Creates an OS account. This API uses a promise to return the result asynchronously. +Creates an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1116,7 +1122,7 @@ This is a system API and cannot be called by third-party applications. | localName | string | Yes | Name of the OS account to create.| | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1168,7 +1174,7 @@ This is a system API and cannot be called by third-party applications. createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo> -Creates an OS account and associates it with the specified domain account. This API uses a promise to return the result asynchronously. +Creates an OS account and associates it with the specified domain account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1183,7 +1189,7 @@ This is a system API and cannot be called by third-party applications. | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1231,13 +1237,13 @@ Obtains information about the OS account to which the current process belongs. T queryCurrentOsAccount(): Promise<OsAccountInfo> -Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. +Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1288,7 +1294,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountById(localId: number): Promise<OsAccountInfo> -Obtains information about an OS account. This API uses a promise to return the result asynchronously. +Obtains information about an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1302,7 +1308,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1348,11 +1354,11 @@ Obtains the type of the OS account to which the current process belongs. This AP getOsAccountTypeFromProcess(): Promise<OsAccountType> -Obtains the type of the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. +Obtains the type of the OS account to which the current process belongs. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1399,13 +1405,13 @@ Obtains the ID of this distributed virtual device. This API uses an asynchronous getDistributedVirtualDeviceId(): Promise<string> -Obtains the ID of this distributed virtual device. This API uses a promise to return the result asynchronously. +Obtains the ID of this distributed virtual device. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1456,7 +1462,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountProfilePhoto(localId: number): Promise<string> -Obtains the profile photo of an OS account. This API uses a promise to return the result asynchronously. +Obtains the profile photo of an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1470,7 +1476,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1526,7 +1532,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> -Sets a profile photo for an OS account. This API uses a promise to return the result asynchronously. +Sets a profile photo for an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1541,7 +1547,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | photo | string | Yes | Profile photo information. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -1593,7 +1599,7 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> -Obtains the OS account ID based on the SN. This API uses a promise to return the result asynchronously. +Obtains the OS account ID based on the SN. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1603,7 +1609,7 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the | ------------ | ------ | ---- | ---------- | | serialNumber | number | Yes | Account SN.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1651,7 +1657,7 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch getSerialNumberByOsAccountLocalId(localId: number): Promise<number> -Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result asynchronously. +Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1661,7 +1667,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1769,7 +1775,7 @@ This is a system API and cannot be called by third-party applications. getBundleIdFromUid(uid: number): Promise<number>; -Obtains the bundle ID based on the UID. This API uses a promise to return the result asynchronously. +Obtains the bundle ID based on the UID. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1781,7 +1787,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | ------------ | | uid | number | Yes | Process UID.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1824,13 +1830,13 @@ This is a system API and cannot be called by third-party applications. isMainOsAccount(): Promise<boolean>; -Checks whether the current process belongs to the main OS account. This API uses a promise to return the result asynchronously. +Checks whether the current process belongs to the main OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1877,7 +1883,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>; -Obtains the constraint source information of an OS account. This API uses a promise to return the result asynchronously. +Obtains the constraint source information of an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1892,7 +1898,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | constraint | string | Yes | Name of the [constraint](#constraints) to query.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e06a5536a8754922e0e82d14162296124f498665 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -0,0 +1,244 @@ +# Privacy Management + +Provides APIs for privacy management, such as management of permission usage records. + +> **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 of this module are system APIs and cannot be called by third-party applications. + +## Modules to Import + +```js +import privacyManager from '@ohos.privacyManager'; +``` + + +## privacyManager.addPermissionUsedRecord + +addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise<number> + +Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result. + +The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. | +| permissionName | string | Yes | Name of the permission.| +| successCount | number | Yes | Number of successful accesses.| +| failCount | number | Yes | Number of failed accesses.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| + +``` + +``` + +**Example** + +```js +var tokenID = appInfo.accessTokenId; // accessTokenId can be obtained by using getApplicationInfo(). +privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0).then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); +}); +``` + +## privacyManager.addPermissionUsedRecord + +addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback<number>): void + +Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result. + +The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. | +| permissionName | string | Yes | Name of the permission.| +| successCount | number | Yes | Number of successful accesses.| +| failCount | number | Yes | Number of failed accesses.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| + +**Example** + +```js +var tokenID = appInfo.accessTokenId; // accessTokenId can be obtained by using getApplicationInfo(). +privacyManager.privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (err, data) => { + console.log(`callback: data->${JSON.stringify(data)}`); +}); +``` + +## privacyManager.getPermissionUsedRecords + +getPermissionUsedRecords(request: PermissionUsedRequest): Promise<PermissionUsedResponse> + +Obtains historical permission usage records. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| request | [PermissionUsedRequest](#permissionusedrequest) | Yes | Request for querying permission usage records. | + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[PermissionUsedResponse](#permissionusedresponse)> | Promise used to return the permission usage records obtained.| + +**Example** + +```js +let request = { + "tokenId": 1, + "isRemote": 1, + "deviceId": "device", + "bundleName": "bundle", + "permissionNames": 1, + "beginTime": 0, + "endTime": 1, + "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, +}; +privacyManager.getPermissionUsedRecords(request).then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); +}); +``` + +## privacyManager.getPermissionUsedRecords + +getPermissionUsedRecords(request: PermissionUsedRequest, callback: AsyncCallback<PermissionUsedResponse>): void + +Obtains historical permission usage records. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| request | [PermissionUsedRequest](#permissionusedrequest) | Yes| Request for querying permission usage records.| +| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback used to return the permission usage records obtained.| + +**Example** + +```js +let request = { + "tokenId": 1, + "isRemote": 1, + "deviceId": "device", + "bundleName": "bundle", + "permissionNames": 1, + "beginTime": 0, + "endTime": 1, + "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, +}; +privacyManager.getPermissionUsedRecords(request, (err, data) => { + console.log(`promise: data->${JSON.stringify(data)}`); +}); +``` + +## PermissionUsageFlag + +Enumerates the modes for querying the permission usage records. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Value| Description | +| ----------------------- | ------ | ---------------------- | +| FLAG_PERMISSION_USAGE_SUMMARY | 0 | Query the permission usage summary.| +| FLAG_PERMISSION_USAGE_DETAIL | 1 | Query detailed permission usage records. | + +## PermissionUsedRequest + +Represents the request for querying permission usage records. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Mandatory | Description | +| -------- | -------------- | ---- | ---------------------------------------- | +| tokenId | number | No | Token ID of the application. | +| isRemote | boolean | No | Whether the token ID belongs to a remote device. The default value is **false**.| +| deviceId | string | No | ID of the device hosting the target application. | +| bundleName | string | No | Bundle name of the target application.| +| permissionNames | Array<string> | No | Permissions to query. | +| beginTime | number | No | Start time of the query, in ms. The default value is **0**, indicating that no start time is set.| +| endTime | number | No | End time of the query, in ms. The default value is **0**, indicating that no end time is set.| +| flag | [PermissionUsageFlag](#permissionusageflag) | Yes | Query mode. The default value is **FLAG_PERMISSION_USAGE_SUMMARY**.| + +## PermissionUsedResponse + +Represents the permission usage records of all applications. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Mandatory | Description | +| -------- | -------------- | ---- | ---------------------------------------- | +| beginTime | number | No | Start time of the query, in ms.| +| endTime | number | No | End time of the query, in ms.| +| bundleRecords | Array<[BundleUsedRecord](#BundleUsedRecord)> | No | Permission usage records obtained. | + +## BundleUsedRecord + +Represents the application access records of an application. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Mandatory | Description | +| -------- | -------------- | ---- | ---------------------------------------- | +| tokenId | number | No | Token ID of the application. | +| isRemote | boolean | No | Whether the token ID belongs to a remote device. The default value is **false**.| +| deviceId | string | No | ID of the device hosting the target application. | +| bundleName | string | No | Bundle name of the target application.| +| permissionRecords | Array<[PermissionUsedRecord](#PermissionUsedRecord)> | No | Permission usage records of the specified application obtained. | + +## PermissionUsedRecord + +Represents the access records of a permission. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Mandatory | Description | +| -------- | -------------- | ---- | ---------------------------------------- | +| permissionName | string | No | Name of the permission. | +| accessCount | number | No | Total number of times that the permission is accessed.| +| rejectCount | number | No | Total number of times that the access to the permission is rejected.| +| lastAccessTime | number | No | Last time when the permission was accessed, in ms.| +| lastRejectTime | number | No | Last time when the access to the permission was rejected, in ms.| +| lastAccessDuration | number | No | Last access duration, in ms.| +| accessRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | No | Access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | +| rejectRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | No | Rejected records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | + +## UsedRecordDetail + +Represents the details of a single access record. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Mandatory | Description | +| -------- | -------------- | ---- | ---------------------------------------- | +| status | number | No | Access status. | +| timestamp | number | No | Access timestamp, in ms.| +| accessDuration | number | No | Access duration, in ms. | diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 86d29eebedf8fb206589a7770a92362a79873c69..b8cbdcc23c001aa24aebe7dfaae2ca06a0fae706 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -7,7 +7,7 @@ ## Modules to Import -```js +``` import radio from '@ohos.telephony.radio' ``` @@ -15,7 +15,7 @@ import radio from '@ohos.telephony.radio' getRadioTech\(slotId: number, callback: AsyncCallback<\{psRadioTech: RadioTechnology, csRadioTech: RadioTechnology\}\>\): void -Obtains the radio access technology (RAT) used by the CS and PS domains. This API uses an asynchronous callback to return the result. +Obtains the radio access technology (RAT) used by the CS and PS domains for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -42,7 +42,7 @@ radio.getRadioTech(slotId, (err, data) =>{ getRadioTech\(slotId: number\): Promise<\{psRadioTech: RadioTechnology, csRadioTech: RadioTechnology\}\> -Obtains the RAT used by the CS and PS domains. This API uses a promise to return the result. +Obtains the RAT used by the CS and PS domains for the SIM card in the specified slot. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -102,7 +102,7 @@ radio.getNetworkState((err, data) =>{ getNetworkState\(slotId: number, callback: AsyncCallback\): void -Obtains the network status. This API uses an asynchronous callback to return the result. +Obtains the network status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -231,7 +231,7 @@ Obtains the ISO country code of the network with which the SIM card in the speci | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ---------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result. which is a country code, for example, **CN** (China).| +| callback | AsyncCallback\ | Yes | Callback used to return the result, which is an ISO country code, for example, **CN** (China).| **Example** @@ -556,10 +556,350 @@ promise.then(data => { }); ``` +## radio.setPrimarySlotId8+ + +setPrimarySlotId(slotId: number, callback: AsyncCallback): void + +Sets the ID of the slot in which the primary card is located. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +```js +let slotId = 0; +radio.setPrimarySlotId(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.setPrimarySlotId8+ + +setPrimarySlotId\(slotId: number\): Promise\ + +Sets the ID of the slot in which the primary card is located. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let slotId = 0; +let promise = radio.setPrimarySlotId(slotId); +promise.then(data => { + console.log(`setPrimarySlotId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setPrimarySlotId fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getIMEI8+ + +getIMEI(callback: AsyncCallback): void + +Obtains the IMEI of the SIM card in a card slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the IMEI does not exist, an empty string is returned.| + +**Example** + +```js +radio.getIMEI((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getIMEI8+ + +getIMEI(slotId: number, callback: AsyncCallback): void + +Obtains the IMEI of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the IMEI does not exist, an empty string is returned.| + +**Example** + +```js +let slotId = 0; +radio.getIMEI(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getIMEI8+ + +getIMEI(slotId?: number): Promise + +Obtains the IMEI of the SIM card in a card slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------ | +| Promise\ | Promise used to return the result. If the IMEI does not exist, an empty string is returned.| + +**Example** + +```js +let slotId = 0; +let promise = radio.getIMEI(slotId); +promise.then(data => { + console.log(`getIMEI success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getIMEI fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getMEID8+ + +getMEID(callback: AsyncCallback): void + +Obtains the MEID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.getMEID((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getMEID8+ + +getMEID(slotId: number, callback: AsyncCallback): void + +Obtains the MEID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.getMEID(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getMEID8+ + +getMEID(slotId?: number): Promise + +Obtains the MEID of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let promise = radio.getMEID(slotId); +promise.then(data => { + console.log(`getMEID success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getMEID fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getUniqueDeviceId8+ + +getUniqueDeviceId(callback: AsyncCallback): void + +Obtains the unique device ID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.getUniqueDeviceId((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getUniqueDeviceId8+ + +getUniqueDeviceId(slotId: number, callback: AsyncCallback): void + +Obtains the unique device ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.getUniqueDeviceId(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getUniqueDeviceId8+ + +getUniqueDeviceId(slotId?: number): Promise + +Obtains the unique device ID of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let promise = radio.getUniqueDeviceId(slotId); +promise.then(data => { + console.log(`getUniqueDeviceId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getUniqueDeviceId fail, promise: err->${JSON.stringify(err)}`); +}); +``` ## RadioTechnology -Enumerates the RATs. +Enumerates the RAT. **System capability**: SystemCapability.Telephony.CoreService @@ -594,7 +934,7 @@ Defines the signal strength. ## NetworkType -Defines the network type. +Enumerates network types. **System capability**: SystemCapability.Telephony.CoreService @@ -610,7 +950,7 @@ Defines the network type. ## NetworkState -Defines the network registration status. +Defines the network status. **System capability**: SystemCapability.Telephony.CoreService @@ -629,7 +969,7 @@ Defines the network registration status. ## RegState -Defines the network registration status. +Defines the network status. **System capability**: SystemCapability.Telephony.CoreService diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index abcc5caff831ee16c84b48e2ec9e5407d6c8a8a2..24f01b3f40d20ae22434cba44c2a6c644d4a95fa 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,6 +1,11 @@ -# Reminder Agent +# reminderAgent -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. + +You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. + +> **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. @@ -23,13 +28,13 @@ Publishes an agent-powered reminder. This API uses an asynchronous callback to r **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| +| callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| **Example** - ```js +```js let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 @@ -37,7 +42,7 @@ Publishes an agent-powered reminder. This API uses an asynchronous callback to r reminderAgent.publishReminder(timer, (err, reminderId) => { console.log("callback, reminderId = " + reminderId); }); - ``` +``` ## reminderAgent.publishReminder @@ -46,20 +51,22 @@ publishReminder(reminderReq: ReminderRequest): Promise<number> Publishes an agent-powered reminder. This API uses a promise callback to return the result. +**Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the published reminder's ID.| **Example** - ```js +```js let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 @@ -67,7 +74,7 @@ Publishes an agent-powered reminder. This API uses a promise callback to return reminderAgent.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); }); - ``` +``` ## reminderAgent.cancelReminder @@ -261,7 +268,7 @@ reminderAgent.cancelAllReminders().then(() => { addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void -Adds a reminder notification slot. This API uses an asynchronous callback to return the result. +Adds a notification slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -269,7 +276,7 @@ Adds a reminder notification slot. This API uses an asynchronous callback to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot to add, only support set its type attribute.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| **Example** @@ -290,7 +297,7 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { addNotificationSlot(slot: NotificationSlot): Promise<void> -Adds a reminder notification slot. This API uses a promise to return the result. +Adds a notification slot. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -298,7 +305,7 @@ Adds a reminder notification slot. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| notification slot to add, only support set its type attribute.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| **Return value** @@ -332,7 +339,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| **Example** @@ -358,7 +365,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 98ff862ea6932d76bed8ba8a8de4a9b452e54a11..50c50f574bbcad706077725e3b4c6f69f3334b1c 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -1,7 +1,10 @@ # Upload and Download +The **request** module provides applications with basic upload, download, and background transmission agent capabilities. -> **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. +> **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 @@ -17,14 +20,16 @@ import request from '@ohos.request'; HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. ``` +var config = { "deviceConfig": { "default": { "network": { "cleartextTraffic": true } - ... + //... } } +} ``` @@ -37,9 +42,9 @@ HTTPS is supported by default. To support HTTP, you need to add **network** to t | Name | Type | Readable | Writable | Description | | -------- | -------- | -------- | -------- | -------- | | NETWORK_MOBILE | number | Yes | No | Whether download is allowed when the cellular network is used. | -| NETWORK_WIFI | number | Yes | No | Whether download is allowed when the WLAN is used. | +| NETWORK_WIFI | number | Yes | No | Whether download is allowed on a WLAN. | | ERROR_CANNOT_RESUME7+ | number | Yes | No | Failure to resume the download due to an error. | -| ERROR_DEVICE_NOT_FOUND7+ | number | Yes | No | Failure to find a storage device such as an SD card. | +| ERROR_DEVICE_NOT_FOUND7+ | number | Yes | No | Failure to find a storage device such as a memory card. | | ERROR_FILE_ALREADY_EXISTS7+ | number | Yes | No | Failure to download the file because it already exists. | | ERROR_FILE_ERROR7+ | number | Yes | No | File operation failure. | | ERROR_HTTP_DATA_ERROR7+ | number | Yes | No | HTTP transmission failure. | @@ -47,7 +52,7 @@ HTTPS is supported by default. To support HTTP, you need to add **network** to t | ERROR_TOO_MANY_REDIRECTS7+ | number | Yes | No | Error caused by too many network redirections. | | ERROR_UNHANDLED_HTTP_CODE7+ | number | Yes | No | Unidentified HTTP code. | | ERROR_UNKNOWN7+ | number | Yes | No | Unknown error. | -| PAUSED_QUEUED_FOR_WIFI7+ | number | Yes | No | Download paused and queuing for WLAN connection, because the file size exceeds the maximum value allowed by a cellular network session. | +| PAUSED_QUEUED_FOR_WIFI7+ | number | Yes | No | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a cellular network session. | | PAUSED_UNKNOWN7+ | number | Yes | No | Download paused due to unknown reasons. | | PAUSED_WAITING_FOR_NETWORK7+ | number | Yes | No | Download paused due to a network connection problem, for example, network disconnection. | | PAUSED_WAITING_TO_RETRY7+ | number | Yes | No | Download paused and then retried. | @@ -151,7 +156,7 @@ Subscribes to the upload progress event. This API uses an asynchronous callback | type | string | Yes | Type of the event to subscribe to. The value is **progress** (upload progress). | | callback | function | Yes | Callback for the upload progress event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -182,10 +187,10 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **headerReceive** (response header). | +| type | string | Yes | Type of the event to subscribe to. The value is **'headerReceive'** (response header). | | callback | function | Yes | Callback for the HTTP Response Header event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -215,10 +220,10 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **progress** (upload progress). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (upload progress). | | callback | function | No | Callback for the upload progress event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -249,10 +254,10 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **headerReceive** (response header). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'headerReceive'** (response header). | | callback | function | No | Callback for the HTTP Response Header event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -340,7 +345,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r | -------- | -------- | -------- | -------- | | url | string | Yes | Resource URL. | | header | object | Yes | HTTP or HTTPS header added to an upload request. | -| method | string | Yes | Request methods available: **POST** and **PUT**. The default value is **POST**. | +| method | string | Yes | Request method, which can be **POST** or **PUT**. The default value is **POST**. | | files | Array<[File](#file)> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | | data | Array<[RequestData](#requestdata)> | Yes | Form data in the request body. | @@ -452,10 +457,10 @@ Subscribes to the download progress event. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **progress** (download progress). | +| type | string | Yes | Type of the event to subscribe to. The value is **'progress'** (download progress). | | callback | function | Yes | Callback for the download progress event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -465,11 +470,10 @@ Parameters of the callback function **Example** ```js - downloadTask.on('progress', function download_callback(receivedSize, totalSize) { + downloadTask.on('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); } ); - }); ``` @@ -487,10 +491,10 @@ Unsubscribes from the download progress event. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **progress** (download progress). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (download progress). | | callback | function | No | Callback for the download progress event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -500,11 +504,10 @@ Parameters of the callback function **Example** ```js - downloadTask .off('progress', function download_callback(receivedSize, totalSize) { - console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); - } + downloadTask .off('progress', function download_callback(receivedSize, totalSize) { + console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); + } ); - }); ``` @@ -522,17 +525,16 @@ Subscribes to a download event. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **complete**: download task completion event.
- **pause**: download task pause event.
- **remove**: download task removal event. | +| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | | callback | function | Yes | Callback used to return the result. | **Example** ```js - downloadTask.on('complete', function callback() { - console.info('Download task completed.'); - } + downloadTask.on('complete', function callback() { + console.info('Download task completed.'); + } ); - }); ``` @@ -550,17 +552,16 @@ Unsubscribes from the download event. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **complete**: download task completion event.
- **pause**: download task pause event.
- **remove**: download task removal event. | +| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | | callback | function | No | Callback used to return the result. | **Example** ```js - downloadTask.off('complete', function callback() { - console.info('Download task completed.'); - } + downloadTask.off('complete', function callback() { + console.info('Download task completed.'); + } ); - }); ``` @@ -578,10 +579,10 @@ Subscribes to the download task failure event. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the subscribed event. The value is **fail** (download failure). | +| type | string | Yes | Type of the subscribed event. The value is **'fail'** (download failure). | | callback | function | Yes | Callback for the download task failure event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -590,11 +591,10 @@ Parameters of the callback function **Example** ```js - downloadTask.on('fail', function callBack(err) { - console.info('Download task failed. Cause:' + err); - } + downloadTask.on('fail', function callBack(err) { + console.info('Download task failed. Cause:' + err); + } ); - }); ``` @@ -612,10 +612,10 @@ Unsubscribes from the download task failure event. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **fail** (download failure). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'fail'** (download failure). | | callback | function | No | Callback for the download task failure event. | -Parameters of the callback function +**callback** parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | @@ -624,11 +624,10 @@ Parameters of the callback function **Example** ```js - downloadTask.off('fail', function callBack(err) { - console.info('Download task failed. Cause:' + err); - } + downloadTask.off('fail', function callBack(err) { + console.info('Download task failed. Cause:' + err); + } ); - }); ``` @@ -948,7 +947,7 @@ Resumes this download task. This API uses an asynchronous callback to return the | enableMetered | boolean | No | Download allowed in metered connections. | | enableRoaming | boolean | No | Download allowed on a roaming network. | | description | string | No | Description of the download session. | -| filePath7+ | string | No | Download path. (The default path is [ERROR:Invalid link:en-us_topic_0000001135742582.xml#xref8132147102215,link:en-us_topic_0000001127125012.xml#section1856519365229](en-us_topic_0000001127125012.xml#section1856519365229)).
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files. | +| filePath7+ | string | No | Download path. (The default path is **'internal://cache/'**.
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files. | | networkType | number | No | Network type allowed for download. | | title | string | No | Title of the download session. | diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 95b60009b09bd8dee7e3a687027d94c070e1b864..fe414f5d9f4b180cc36d1dbb3c36889924d3840c 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,5 +1,6 @@ # RPC +This module implements communication between processes, including inter-process communication (IPC) on a single device and Remote Procedure Call (RPC) between processes of difference devices. IPC is implemented based on the Binder driver, and RPC is based on the software bus driver. > **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. @@ -2397,7 +2398,7 @@ Unmarshals this sequenceable object from a **MessageParcel** object. ## IRemoteBroker -Obtains a remote proxy object. +Provides the holder of a remote proxy object. ### asObject @@ -2503,7 +2504,7 @@ Obtains the interface. ### sendRequest(deprecated) > **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8). +> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8). sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean @@ -2652,7 +2653,7 @@ Provides methods to implement **IRemoteObject**. ### sendRequest(deprecated) > **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8-2). +> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8-2). sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean @@ -3470,7 +3471,7 @@ A constructor used to create a **RemoteObject** object. ### sendRequest(deprecated) > **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8-4). +> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8-4). sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean 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 3cbaa21a08db64be6443dea8b0d42a3ead9e9efc..d75b957512e60e55aacfac1fdce2fdf063eb9c56 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,8 +1,8 @@ # Screen Lock Management - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> The initial APIs of this module are supported since API version … Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -17,17 +17,17 @@ import screenlock from '@ohos.screenLock'; isScreenLocked(callback: AsyncCallback<boolean>): void -Checks whether the screen is locked. This method uses an asynchronous callback to return the result. +Checks whether the screen is locked. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If **true** is returned, the screen is locked. If **false** is returned, the screen is not locked. | +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Returns **true** if the screen is locked; returns **false** otherwise.| + +**Example** -- Example - ```js screenlock.isScreenLocked((err, data)=>{ if (err) { @@ -43,17 +43,17 @@ Checks whether the screen is locked. This method uses an asynchronous callback t isScreenLocked(): Promise<boolean> -Checks whether the screen is locked. This method uses a promise to return the result. +Checks whether the screen is locked. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Return Values - | Type | Description | - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. | +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** -- Example - ```js screenlock.isScreenLocked().then((data) => { console.log('isScreenLocked success: data -> ${JSON.stringify(data)}'); @@ -68,19 +68,18 @@ Checks whether the screen is locked. This method uses a promise to return the re isSecureMode(callback: AsyncCallback<boolean>): void -Checks whether a device is in secure mode. This method uses an asynchronous callback to return the result. +Checks whether a device is in secure mode. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Returns **true** if the device is in secure mode; returns **false** otherwise.| -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If **true** is returned, the device is in secure mode. If **false** is returned, the device is not in secure mode. | +**Example** -- Example - ```js screenlock.isSecureMode((err, data)=>{ if (err) { @@ -96,17 +95,17 @@ Checks whether a device is in secure mode. This method uses an asynchronous call isSecureMode(): Promise<boolean> -Checks whether a device is in secure mode. This method uses a promise to return the result. +Checks whether a device is in secure mode. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Return Values - | Type | Description | - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. | +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** -- Example - ```js screenlock.isSecureMode().then((data) => { console.log('isSecureMode success: data->${JSON.stringify(data)}'); @@ -121,21 +120,20 @@ Checks whether a device is in secure mode. This method uses a promise to return unlockScreen(callback: AsyncCallback<void>): void -Unlocks the screen. This method uses an asynchronous callback to return the result. +Unlocks the screen. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation failed, an error message is returned.| -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | Callback function. If the callback fails, an error message is returned. | +**Example** -- Example - ```js - screenlock.unlockScreen((err)=>{ + screenlock.unlockScreen((err) => { if (err) { console.error('unlockScreen callback error -> ${JSON.stringify(err)}'); return; @@ -149,17 +147,17 @@ Unlocks the screen. This method uses an asynchronous callback to return the resu unlockScreen(): Promise<void> -Unlocks the screen. This method uses a promise to return the result. +Unlocks the screen. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Return Values - | Type | Description | - | -------- | -------- | - | Promise<void> | Promise used to return the result. | +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** -- Example - ```js screenlock.unlockScreen().then(() => { console.log('unlockScreen success'); @@ -167,3 +165,142 @@ Unlocks the screen. This method uses a promise to return the result. console.error('unlockScreen fail, promise: err->${JSON.stringify(err)}'); }); ``` + +## screenlock.on9+ + +on(type: 'beginWakeUp' | 'endWakeUp' | 'beginScreenOn' | 'endScreenOn' | 'beginScreenOff' | 'endScreenOff' | 'unlockScreen' | 'beginExitAnimation', callback: Callback\): void + +Subscribes to screen lock status changes. + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **'beginWakeUp'**: Wakeup starts.
- **'endWakeUp'**: Wakeup ends.
- **'beginScreenOn'**: Screen turn-on starts.
- **'endScreenOn'**: Screen turn-on ends.
- **'beginScreenOff'**: Screen turn-off starts.
- **'endScreenOff'**: Screen turn-off ends.
- **'unlockScreen'**: The screen is unlocked.
- **'beginExitAnimation'**: Animation starts to exit. | +| callback | Callback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + screenlock.on('beginWakeUp', () => { + console.log('beginWakeUp triggered'); + }); + ``` + +## screenlock.on9+ + +on(type: 'beginSleep' | 'endSleep' | 'changeUser', callback: Callback\): void + +Subscribes to screen lock status changes. + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **'beginSleep'**: The screen enters sleep mode.
- **'endSleep'**: The screen exits sleep mode.
- **'changeUser'**: The user is switched.| +| callback | Callback\ | Yes| Callback used to return the result. | + +**Example** + + ```js + screenlock.on('beginSleep', (why) => { + console.log('beginSleep triggered:' + why); + }); + ``` +## screenlock.on9+ + +on(type: 'screenlockEnabled', callback: Callback\): void + +Subscribes to screen lock status changes. + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **'screenlockEnabled'**: Screen lock is enabled.| +| callback | Callback\ | Yes| Callback used to return the result. | + +**Example** + + ```js + screenlock.on('screenlockEnabled', (isEnabled) => { + console.log('screenlockEnabled triggered, result:' + isEnabled); + }); + ``` + +## screenlock.off9+ + +off(type: 'beginWakeUp' | 'endWakeUp' | 'beginScreenOn' | 'endScreenOn' | 'beginScreenOff' | 'endScreenOff' + | 'unlockScreen' | 'beginExitAnimation' | 'screenlockEnabled' | 'beginSleep' | 'endSleep' | 'changeUser', callback: Callback\): void + +Unsubscribes from screen lock status changes. + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **'beginWakeUp'**: Wakeup starts.
- **'endWakeUp'**: Wakeup ends.
- **'beginScreenOn'**: Screen turn-on starts.
- **'endScreenOn'**: Screen turn-on ends.
- **'beginScreenOff'**: Screen turn-off starts.
- **'endScreenOff'**: Screen turn-off ends.
- **'unlockScreen'**: The screen is unlocked.
- **'beginExitAnimation'**: Animation starts to exit.
- **'screenlockEnabled'**: Screen lock is enabled.
- **'beginSleep'**: The screen enters sleep mode.
- **'endSleep'**: The screen exits sleep mode.
- **'changeUser'**: The user is switched.| +| callback | Callback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + screenlock.off('beginWakeUp', () => { + console.log("callback"); + }); + ``` + +## screenlock.sendScreenLockEvent9+ + +sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback\): void + +Sends an event to the screen lock service. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | String | Yes| Event type.
- **'unlockScreenResult'**: Screen unlock result.
- **'screenDrawDone'**: Screen drawing is complete.| +| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **0**: The unlock failed.
- **2**: The unlock was canceled.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { + console.log('sending result:' + result); + }); + ``` + +## screenlock.sendScreenLockEvent9+ + +sendScreenLockEvent(event: String, parameter: number): Promise + +Sends an event to the screen lock service. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | String | Yes| Event type.
- **'unlockScreenResult'**: Screen unlock result.
- **'screenDrawDone'**: Screen drawing is complete.| +| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **0**: The unlock failed.
- **2**: The unlock was canceled.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```js + screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((err, result) => { + console.log('sending result:' + result); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-securityLabel.md b/en/application-dev/reference/apis/js-apis-securityLabel.md index e552e2032a4827e0f7877235d242478a3bff0a81..a2219288f3b852337ee03ab9f7003adf02dd51b4 100644 --- a/en/application-dev/reference/apis/js-apis-securityLabel.md +++ b/en/application-dev/reference/apis/js-apis-securityLabel.md @@ -1,10 +1,10 @@ # Security Label +The secuityLabel module provides APIs to manage file data security levels, including obtaining and setting file data security levels. + > **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 of this module can be used to obtain and set file security levels. - ## Modules to Import ```js @@ -15,34 +15,26 @@ import securityLabel from '@ohos.securityLabel'; Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). -Application sandbox path of a file or directory = Application directory + File name or directory name - -For example, if the application directory obtained by using **getOrCreateLocalDir** is **dir** and the file name is **xxx.txt**, the application sandbox path of the file is as follows: - ```js -let path = dir + "/xxx.txt"; -``` - -The file descriptor is as follows: - -```js -let fd = fileio.openSync(path, 0o102, 0o666); +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); +let path = context.getFilesDir(); ``` ## securityLabel.setSecurityLabel -setSecurityLabel(path:string, dataLevel:string):Promise<void> +setSecurityLabel(path:string, type:dataLevel):Promise<void> Sets the security label for a file in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.File.DistributedFile +**System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | -------------------------------------------- | -| path | string | Yes | File path. | -| dataLevel | string | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------------- | +| path | string | Yes | File path. | +| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| **Return value** @@ -53,7 +45,8 @@ Sets the security label for a file in asynchronous mode. This API uses a promise **Example** ```js - securityLabel.setSecurityLabel(path, dataLevel).then(function(){ + let type = "s4"; + securityLabel.setSecurityLabel(path, type).then(function(){ console.info("setSecurityLabel successfully"); }).catch(function(error){ console.info("setSecurityLabel failed with error:" + error); @@ -62,46 +55,48 @@ Sets the security label for a file in asynchronous mode. This API uses a promise ## securityLabel.setSecurityLabel -setSecurityLabel(path:string, dataLevel:string, callback: AsyncCallback<void>):void +setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void>):void Sets the security label for a file in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.File.DistributedFile +**System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | -------------------------------------------- | | path | string | Yes | File path. | -| dataLevel | string | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js - securityLabel.setSecurityLabel(path, dataLevel, function(error){ + let type = "s4"; + securityLabel.setSecurityLabel(path, type, function(error){ console.info("setSecurityLabel:" + JSON.stringify(error)); }); ``` ## securityLabel.setSecurityLabelSync -setSecurityLabelSync(path:string, dataLevel:string):void +setSecurityLabelSync(path:string, type:dataLevel):void Sets the security label for a file in synchronous mode. -**System capability**: SystemCapability.FileManagement.File.DistributedFile +**System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name | Type | Mandatory| Description | | --------- | ------ | ---- | -------------------------------------------- | | path | string | Yes | File path. | -| dataLevel | string | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| **Example** ```js -securityLabel.setSecurityLabelSync(path, dataLevel); +let type = "s4"; +securityLabel.setSecurityLabelSync(path, type); ``` ## securityLabel.getSecurityLabel @@ -110,7 +105,7 @@ getSecurityLabel(path:string):Promise<string> Obtains the security label of a file in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.File.DistributedFile +**System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -127,8 +122,9 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi **Example** ```js - securityLabel.getSecurityLabel(path).then(function(dataLevel){ - console.log("getSecurityLabel successfully:" + dataLevel); + let type = "s4"; + securityLabel.getSecurityLabel(path).then(function(type){ + console.log("getSecurityLabel successfully:" + type); }).catch(function(error){ console.log("getSecurityLabel failed with error:" + error); }); @@ -140,7 +136,7 @@ getSecurityLabel(path:string, callback:AsyncCallback<string>): void Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.File.DistributedFile +**System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -152,8 +148,9 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb **Example** ```js - securityLabel.getSecurityLabel(function(error, dataLevel){ - console.log("getSecurityLabel successfully:" + dataLevel); + let type = "s4"; + securityLabel.getSecurityLabel(path,function(error, type){ + console.log("getSecurityLabel successfully:" + type); }); ``` ## securityLabel.getSecurityLabelSync @@ -162,7 +159,7 @@ getSecurityLabelSync(path:string):string Obtains the security label of a file in synchronous mode. -**System capability**: SystemCapability.FileManagement.File.DistributedFile +**System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index aab544f7f78bd2b755ab24443aa1d0acd5d683c1..16dbb61057c1ab6f8d6c34462004d8babbacb448 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -886,11 +886,7 @@ Subscribes to only one data change of the proximity sensor. **Example** ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { - if (error) { - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - } + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { console.info('Distance: ' + data.distance); } ); @@ -1350,8 +1346,6 @@ off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityRes Unsubscribes from sensor data changes. -**Required permission**: ohos.permission.READ_HEALTH_DATA (a system permission) - **System capability**: SystemCapability.Sensors.Sensor **Parameters** @@ -1404,8 +1398,6 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); Unsubscribes from sensor data changes. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) - **System capability**: SystemCapability.Sensors.Sensor **Parameters** @@ -1487,6 +1479,8 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerR Unsubscribes from sensor data changes. +**Required permissions**: ohos.permission.ACTIVITY_MOTION + **System capability**: SystemCapability.Sensors.Sensor **Parameters** @@ -1739,7 +1733,7 @@ Obtains the geomagnetic field of a geographic location. This API uses a promise **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| **Example** ```js @@ -1899,7 +1893,6 @@ Obtains the angle change between two rotation matrices. This API uses a callback err.message); return; } - console.info("SensorJsAPI--->Successed to get getAngleModifiy interface get data: " + data.x); for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } @@ -1967,7 +1960,6 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r err.message); return; } - console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } @@ -2034,7 +2026,6 @@ Converts a rotation vector into a quaternion. This API uses a callback to return err.message); return; } - console.info("SensorJsAPI--->Successed to get createQuaternion interface get data: " + data.x); for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } @@ -2169,7 +2160,6 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th err.message); return; } - console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]) } diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 73be3dd9605235802e6bcd78992ff47d6cd1c469..a546ee0cc3fc95d286b1f2a835998426372c874a 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,16 +1,15 @@ # Settings +This module provides APIs for setting data items. + > **NOTE** > > The initial APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -This module provides APIs for setting data items. - - ## Modules to Import -```typescript +```ts import settings from '@ohos.settings'; ``` @@ -28,7 +27,8 @@ Obtains the URI of a data item. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS
    • Time format: settings.date.TIME_FORMAT
  • Custom data items
| +| settings.display.SCREEN_BRIGHTNESS_STATUS | string | Yes| Brightness of the target data item.| +| settings.date.TIME_FORMAT | string | Yes| Time format of the target data item. Data | **Return value** @@ -38,7 +38,7 @@ Obtains the URI of a data item. **Example** -```typescript +```ts // Obtain the URI of a data item. let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); ``` @@ -67,7 +67,7 @@ Obtains the value of a data item. **Example** -```typescript +```ts import featureAbility from '@ohos.ability.featureAbility'; // Obtain the value of settings.display.SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). @@ -95,7 +95,7 @@ If the specified data item exists in the database, the **setValueSync** method u | -------- | -------- | -------- | -------- | | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| | name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: **settings.display.SCREEN_BRIGHTNESS_STATUS**
    • Time format: **settings.date.TIME_FORMAT**
  • Custom data items
| -| value | string | Yes| Value of the data item.| +| value | string | Yes| Value of the data item.The value of range with the service.| **Return value** @@ -105,7 +105,7 @@ If the specified data item exists in the database, the **setValueSync** method u **Example** -```typescript +```ts import featureAbility from '@ohos.ability.featureAbility'; // Update the value of settings.display.SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 3344e47d14f8d615b1f81e75f92251dc4e8c8287..acad2c7f0223074ef134389ddeac17b8f8d47455 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -17,13 +17,13 @@ isSimActive\(slotId: number, callback: AsyncCallback\): void Checks whether the SIM card in the specified slot is activated. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | **Example** @@ -41,13 +41,13 @@ isSimActive\(slotId: number\): Promise Checks whether the SIM card in the specified slot is activated. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** @@ -73,7 +73,7 @@ getDefaultVoiceSlotId\(callback: AsyncCallback\): void Obtains the default slot ID of the SIM card that provides voice services. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -96,7 +96,7 @@ getDefaultVoiceSlotId\(\): Promise Obtains the default slot ID of the SIM card that provides voice services. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Return value** @@ -121,13 +121,13 @@ hasOperatorPrivileges(slotId: number, callback: AsyncCallback\): void Checks whether the application (caller) has been granted the operator permission. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -144,13 +144,13 @@ hasOperatorPrivileges(slotId: number): Promise Checks whether the application (caller) has been granted the operator permission. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** @@ -175,14 +175,14 @@ getISOCountryCodeForSim\(slotId: number, callback: AsyncCallback\): voi Obtains the ISO country code of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result, which is a country code, for example, **CN** (China).| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback\ | Yes | Callback used to return the result, which is an ISO country code, for example, **CN** (China).| **Example** @@ -199,19 +199,19 @@ getISOCountryCodeForSim\(slotId: number\): Promise Obtains the ISO country code of the SIM card in the specified slot. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** | Type | Description | | ----------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result, which is a country code, for example, **CN** (China).| +| Promise\ | Promise used to return the result, which is an ISO country code, for example, **CN** (China).| **Example** @@ -231,13 +231,13 @@ getSimOperatorNumeric\(slotId: number, callback: AsyncCallback\): void Obtains the public land mobile network (PLMN) ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -255,13 +255,13 @@ getSimOperatorNumeric\(slotId: number\): Promise Obtains the PLMN ID of the SIM card in the specified slot. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** @@ -287,13 +287,13 @@ getSimSpn\(slotId: number, callback: AsyncCallback\): void Obtains the service provider name (SPN) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -311,13 +311,13 @@ getSimSpn\(slotId: number\): Promise Obtains the SPN of the SIM card in the specified slot. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** @@ -343,13 +343,13 @@ getSimState\(slotId: number, callback: AsyncCallback\): void Obtains the status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\<[SimState](#simstate)\> | Yes | Callback used to return the result. For details, see [SimState](#simstate). | **Example** @@ -367,13 +367,13 @@ getSimState\(slotId: number\): Promise Obtains the status of the SIM card in the specified slot. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** @@ -398,13 +398,13 @@ getCardType\(slotId: number, callback: AsyncCallback\): void Obtains the type of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\<[CardType](#cardtype7)\> | Yes | Callback used to return the result. | **Example** @@ -422,13 +422,13 @@ getCardType\(slotId: number\): Promise Obtains the type of the SIM card in the specified slot. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** @@ -454,18 +454,18 @@ hasSimCard\(slotId: number, callback: AsyncCallback\): void Checks whether the SIM card in the specified slot is installed. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | **Example** -```js +```jsjs sim.hasSimCard(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -478,13 +478,13 @@ hasSimCard\(slotId: number\): Promise Checks whether the SIM card in the specified slot is installed. This API uses a promise to return the result. -**System capability**: SystemCapability.Communication.CoreService +**System capability**: SystemCapability.Telephony.CoreService **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** @@ -503,58 +503,1271 @@ promise.then(data => { }); ``` +## sim.getSimAccountInfo7+ -## sim.getMaxSimCount7+ +getSimAccountInfo(slotId: number, callback: AsyncCallback): void -getMaxSimCount\(\): number +Obtains account information of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -Obtains the number of card slots. +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[IccAccountInfo](#IccAccountInfo7)\> | Yes | Callback used to return the result. For details, see [IccAccountInfo](#IccAccountInfo7).| + +**Example** + +```js +sim.getSimAccountInfo(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getSimAccountInfo7+ + +getSimAccountInfo(slotId: number): Promise + +Obtains account information of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. -**System capability**: SystemCapability.Communication.CoreService +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------------------ | -| number | Number of card slots.| +| Type | Description | +| -------------------------------------------- | ------------------------------------------ | +| Promise<[IccAccountInfo](#IccAccountInfo7)\> | Promise used to return the result.| **Example** ```js -console.log("Result: "+ sim.getMaxSimCount()) +let promise = sim.getSimAccountInfo(0); +promise.then(data => { + console.log(`getSimAccountInfo success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getSimAccountInfo fail, promise: err->${JSON.stringify(err)}`); +}); ``` +## sim.getActiveSimAccountInfoList8+ -## SimState +getActiveSimAccountInfoList(callback: AsyncCallback>): void -Enumerates SIM card states. +Obtains the account information list of the active SIM card. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| --------------------- | ---- | ---------------------------------------------------------- | -| SIM_STATE_UNKNOWN | 0 | The SIM card is in **unknown** state; that is, the SIM card status cannot be obtained. | -| SIM_STATE_NOT_PRESENT | 1 | The SIM card is in **not present** state; that is, no SIM card is inserted into the slot. | -| SIM_STATE_LOCKED | 2 | The SIM card is in **locked** state; that is, the SIM card is locked by the personal identification number (PIN), PIN unblocking key (PUK), or network. | -| SIM_STATE_NOT_READY | 3 | The SIM card is in **not ready** state; that is, the SIM card is present but cannot work properly. | -| SIM_STATE_READY | 4 | The SIM card is in **ready** state; that is, the SIM card is present and is working properly. | -| SIM_STATE_LOADED | 5 | The SIM card is in **loaded** state; that is, the SIM card is present and all its files have been loaded.| +**Parameters** -## CardType7+ +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\\> | Yes | Callback used to return the result.| -Enumerates card types. +**Example** + +```js +sim.getActiveSimAccountInfoList(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getActiveSimAccountInfoList8+ + +getActiveSimAccountInfoList(): Promise>; + +Obtains the account information list of the active SIM card. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CoreService -| Name| Value| Description| -| ----- | ----- | ----- | -|UNKNOWN_CARD | -1 | Unknown| -|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM)| -|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM)| -|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM)| -|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM)| -|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card| -|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card| -|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card| -|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM)| -|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM)| +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ---------------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getActiveSimAccountInfoList(); +promise.then(data => { + console.log(`getActiveSimAccountInfoList success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getActiveSimAccountInfoList fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.setDefaultVoiceSlotId7+ + +setDefaultVoiceSlotId(slotId: number, callback: AsyncCallback): void + +Sets the default slot ID of the SIM card that provides voice services. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.setDefaultVoiceSlotId(0,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.setDefaultVoiceSlotId7+ + +setDefaultVoiceSlotId(slotId: number): Promise\ + +Sets the default slot ID of the SIM card that provides voice services. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let promise = sim.setDefaultVoiceSlotId(0); +promise.then(data => { + console.log(`setDefaultVoiceSlotId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setDefaultVoiceSlotId fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**setShowName**8+ + +setShowName\(slotId: number, name: string,callback: AsyncCallback\): void + +Sets a display name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| name | string | Yes | SIM card name. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +const name='China Mobile'; +sim.setShowName(0, name,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## sim.**setShowName**8+ + +setShowName\(slotId: number, name: string\): Promise\ + +Sets a display name for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| name | string | Yes | SIM card name. | + +**Return value** + +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +const name='China Mobile'; +let promise = sim.setShowName(0,name); +promise.then(data => { + console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setShowName fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**getShowName**8+ + +getShowName(slotId: number, callback: AsyncCallback): void + +Obtains the name of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<string> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getShowName(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**getShowName**8+ + +getShowName(slotId: number): Promise + +Obtains the name of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------------- | -------------------------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getShowName(0); +promise.then(data => { + console.log(`getShowName success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getShowName fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**setShowNumber**8+ + +setShowNumber\(slotId: number, number: string,callback: AsyncCallback\): void + +Sets a display number for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| number | string | Yes | SIM card number. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let number='+861xxxxxxxxxx'; +sim.setShowNumber(0, number,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**setShowNumber**8+ + +setShowNumber\(slotId: number,number: string\): Promise\ + +Sets a display number for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| number | string | Yes | SIM card number. | + +**Return value** + +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let number='+861xxxxxxxxxx'; +let promise = sim.setShowNumber(0,number); +promise.then(data => { + console.log(`setShowNumber success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setShowNumber fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**getShowNumber**8+ + +getShowNumber(slotId: number,callback: AsyncCallback): void + +Obtains the display number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<string> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getShowNumber(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**getShowNumber**8+ + +getShowNumber(slotId: number): Promise + +Obtains the display number of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getShowNumber(0); +promise.then(data => { + console.log(`getShowNumber success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getShowNumber fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**activateSim**8+ + +activateSim(slotId: number, callback: AsyncCallback): void + +Activates the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.activateSim(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**activateSim**8+ + +activateSim(slotId: number): Promise\ + +Activates the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let promise = sim.activateSim(0); +promise.then(data => { + console.log(`activateSim success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`activateSim fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**deactivateSim**8+ + +deactivateSim(slotId: number, callback: AsyncCallback): void + +Deactivates the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.deactivateSim(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**deactivateSim**8+ + +deactivateSim(slotId: number): Promise\ + +Deactivates the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let promise = sim.deactivateSim(0); +promise.then(data => { + console.log(`deactivateSim success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`deactivateSim fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.setLockState7+ + +setLockState(slotId: number, options: LockInfo, callback: AsyncCallback): void + +Sets the lock status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | +| options | [LockInfo](#LockInfo8) | Yes | Lock information.
- **lockType**: [LockType](#LockType8)
- **password**: string
- **state**: [LockState](#LockState8) | + +**Example** + +```js +LockInfo.lockType = 1; +LockInfo.password = "1234"; +LockInfo.state = 0; +sim.setLockState(0, LockInfo, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.setLockState7+ + +setLockState(slotId: number, options: LockInfo): Promise + +Sets the lock status of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| options | [LockInfo](#LockInfo8) | Yes | Lock information.
- **lockType**: [LockType](#LockType8)
**password**: string
**state**: [LockState](#LockState8) | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | -------------------------------------------- | +| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| + +**Example** + +```js +LockInfo.lockType = 1; +LockInfo.password = "1234"; +LockInfo.state = 0; +let promise = sim.setLockState(0, LockInfo); +promise.then(data => { + console.log(`setLockState success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setLockState fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getLockState8+ + +getLockState(slotId: number, lockType: LockType, callback: AsyncCallback): void + +Obtains the lock status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | --------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback\<[LockState](#LockState8)\> | Yes | Callback used to return the result. | +| options | [LockType](#LockType8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN2 lock| + +**Example** + +```js +sim.getLockState(0, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getLockState8+ + +getLockState(slotId: number, lockType: LockType): Promise + +Obtains the lock status of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------- | ---- | --------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| options | [LockType](#LockType8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN2 lock| + +**Return value** + +| Type | Description | +| ---------------------------------- | -------------------------------------------- | +| Promise<[LockState](#LockState8)\> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getLockState(0, 1); +promise.then(data => { + console.log(`getLockState success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getLockState fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.alterPin7+ + +alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback): void + +Changes the PIN. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | +| newPin | string | Yes | New PIN. | +| oldPin | string | Yes | Old PIN. | + +**Example** + +```js +sim.alterPin(0, "1234", "0000"(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.alterPin7+ + +alterPin(slotId: number, newPin: string, oldPin: string): Promise; + +Changes the PIN. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| newPin | string | Yes | New PIN. | +| oldPin | string | Yes | Old PIN. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------------- | +| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.alterPin(0, "1234", "0000"); +promise.then(data => { + console.log(`alterPin success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`alterPin fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.alterPin28+ + +alterPin2(slotId: number, newPin2: string, oldPin2: string, callback: AsyncCallback): void + +Changes PIN 2. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | +| newPin2 | string | Yes | New PIN. | +| oldPin2 | string | Yes | Old PIN. | + +**Example** + +```js +sim.alterPin2(0, "1234", "0000", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.alterPin28+ + +alterPin2(slotId: number, newPin2: string, oldPin2: string): Promise + +Changes PIN 2. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| newPin2 | string | Yes | New PIN. | +| oldPin2 | string | Yes | Old PIN. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------------- | +| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.alterPin2(0, "1234","0000"); +promise.then(data => { + console.log(`alterPin2 success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`alterPin2 fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**unlockPin**7+ + +unlockPin(slotId: number,pin: string ,callback: AsyncCallback): void + +Unlocks the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| pin | string | Yes | PIN of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | + +**Example** + +```js +let pin='1234'; +sim.unlockPin(0, pin,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**unlockPin**7+ + +unlockPin(slotId: number,pin: string): Promise<LockStatusResponse\> + +Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| pin | string | Yes | PIN of the SIM card. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | -------------------------------------------------- | +| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| + +**Example** + +```js +let pin='1234'; +let promise = sim.unlockPin(0,pin); +promise.then(data => { + console.log(`unlockPin success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`unlockPin fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**unlockPuk**7+ + +unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback): void + +Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| newPin | string | Yes | New PIN. | +| puk | string | Yes | PUK of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | + +**Example** + +```js +let puk='1xxxxxxx'; +let newPin='1235'; +sim.unlockPuk(0, newPin,puk,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**unlockPuk**7+ + +unlockPuk(slotId: number,newPin: string,puk: string): Promise<LockStatusResponse\> + +Unlocks the PUK of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| newPin | string | Yes | New PIN. | +| puk | string | Yes | PUK of the SIM card. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | -------------------------------------------------- | +| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| + +**Example** + +```js +let puk='1xxxxxxx'; +let newPin='1235'; +let promise = sim.unlockPuk(0,newPin,puk); +promise.then(data => { + console.log(`unlockPuk success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`unlockPuk fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**unlockPin**28+ + +****unlockPin2****(slotId: number,pin2: string ,callback: AsyncCallback): void + +Unlocks PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| pin2 | string | Yes | PIN of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | + +**Example** + +```js +let pin2='1234'; +sim.unlockPin2(0, pin2,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**unlockPin**28+ + +unlockPin2(slotId: number,pin2: string): Promise<LockStatusResponse\> + +Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| pin2 | string | Yes | PIN of the SIM card. | + +**Return value** + +| Type | Description | +| ----------------------------------------------------- | -------------------------------------------------- | +| Promise\<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| + +**Example** + +```js +let pin2='1234'; +let promise = sim.unlockPin2(0,pin2); +promise.then(data => { + console.log(`unlockPin2 success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`unlockPin2 fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.**unlockPuk**28+ + +unlockPuk2(slotId: number,newPin2: string,puk2: string ,callback: AsyncCallback): void + +Unlocks PUK 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| newPin2 | string | Yes | New PIN. | +| puk2 | string | Yes | PUK of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | + +**Example** + +```js +let puk2='1xxxxxxx'; +let newPin2='1235'; +sim.unlockPuk2(0, newPin2,puk2,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.**unlockPuk2**8+ + +unlockPuk2slotId: number,newPin2: string,puk2: string): Promise<LockStatusResponse\> + +Unlocks PUK 2 of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| newPin2 | string | Yes | New PIN. | +| puk2 | string | Yes | PUK of the SIM card. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | -------------------------------------------------- | +| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| + +**Example** + +```js +let puk2='1xxxxxxx'; +let newPin2='1235'; +let promise = sim.unlockPuk2(0,newPin2,puk2); +promise.then(data => { + console.log(`unlockPuk2 success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`unlockPuk2 fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getMaxSimCount7+ + +getMaxSimCount\(\): number + +Obtains the number of card slots. + +**System capability**: SystemCapability.Telephony.CoreService + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| number | Number of card slots.| + +**Example** + +```js +console.log("Result: "+ sim.getMaxSimCount()) +``` + + +## SimState + +Enumerates SIM card states. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| --------------------- | ---- | ---------------------------------------------------------- | +| SIM_STATE_UNKNOWN | 0 | The SIM card is in **unknown** state; that is, the SIM card status cannot be obtained. | +| SIM_STATE_NOT_PRESENT | 1 | The SIM card is in **not present** state; that is, no SIM card is inserted into the card slot. | +| SIM_STATE_LOCKED | 2 | The SIM card is in **locked** state; that is, the SIM card is locked by the personal identification number (PIN), PIN unblocking key (PUK), or network. | +| SIM_STATE_NOT_READY | 3 | The SIM card is in **not ready** state; that is, the SIM card has been installed but cannot work properly. | +| SIM_STATE_READY | 4 | The SIM card is in **ready** state; that is, the SIM card has been installed and is working properly. | +| SIM_STATE_LOADED | 5 | The SIM card is in **loaded** state; that is, the SIM card is present and all its files have been loaded.| + +## CardType7+ + +Enumerates card types. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name| Value| Description| +| ----- | ----- | ----- | +|UNKNOWN_CARD | -1 | Unknown| +|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM)| +|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM)| +|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM)| +|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM)| +|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card| +|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card| +|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card| +|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM)| +|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM)| + +## LockType8+ + +Enumerates lock types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------- | ---- | ----------- | +| PIN_LOCK | 1 | SIM card password lock| +| FDN_LOCK | 2 | Fixed dialing lock | + +## LockState8+ + +Enumerates lock states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------- | ---- | ---------- | +| LOCK_OFF | 0 | The lock is off.| +| LOCK_ON | 1 | The lock is on.| + +## **PersoLockType**8+ + +Enumerates personalized lock types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| ------------ | ---- | ----------------------------------------------- | +| PN_PIN_LOCK | 0 | Personalized network PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PN_PUK_LOCK | 1 | Personalized network PUK lock. | +| PU_PIN_LOCK | 2 | Personalized network subset PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PU_PUK_LOCK | 3 | Personalized network subset PUK lock. | +| PP_PIN_LOCK | 4 | Personalized service provider PIN lock. For details, see *3GPP TS 22.022 [33]*.| +| PP_PUK_LOCK | 5 | Personalized service provider PUK lock. | +| PC_PIN_LOCK | 6 | Personalized corporate PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PC_PUK_LOCK | 7 | Personalized corporate PUK lock. | +| SIM_PIN_LOCK | 8 | Personalized SIM card PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| SIM_PUK_LOCK | 9 | Personalized SIM card PUK lock. | + +## **LockStatusResponse**7+ + +Defines the lock status response. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| --------------- | ------ | ------------------ | +| result | number | Operation result. | +| remain?: number | number | Remaining attempts (can be null).| + +## **LockInfo**8+ + +Defines the personalized lock status response. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| -------- | --------- | ------ | +| lockType | LockType | Lock type.| +| password | string | Password. | +| state | LockState | Lock state.| + +## **PersoLockInfo**8+ + +Defines the personalized lock information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| -------- | ------------- | ------------ | +| lockType | PersoLockType | Personalized lock type.| +| password | string | Password. | + +## **IccAccountInfo**7+ + +Defines the ICC account information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ---------- | ------- | ---------------- | +| simId | number | SIM card ID. | +| slotIndex | number | Card slot ID. | +| isEsim | boolean | Whether the SIM card is an eSim card.| +| isActive | boolean | Whether the card is activated. | +| iccId | string | ICCID number. | +| showName | string | SIM card display name. | +| showNumber | string | SIM card display number. | diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index a264817ec018ad6a7fe22888ea0f7a3c5f223fcf..11fdf806794469274ea30ee3b4797b42f9041965 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -6,7 +6,7 @@ ## Modules to Import -``` +```js import sms from '@ohos.telephony.sms'; ``` @@ -22,13 +22,13 @@ Creates an SMS message instance based on the protocol data unit (PDU) and the sp | Name | Type | Mandatory| Description | | ------------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | -| pdu | Array<number> | Yes | PDU, which is obtained from the received SMS message. | +| pdu | Array<number> | Yes | Protocol data unit, which is obtained from the received SMS message. | | specification | string | Yes | SMS protocol type.
- **3gpp**: GSM/UMTS/LTE SMS
- **3gpp2**: CDMA SMS| | callback | AsyncCallback<[ShortMessage](#shortmessage)> | Yes | Callback used to return the result. | **Example** -``` +```js const specification = '3gpp'; // Display PDUs using numbers in an array, for example, [0x08, 0x91, ...]. const pdu = [0x08, 0x91]; @@ -50,10 +50,10 @@ Creates an SMS message instance based on the PDU and the specified SMS protocol. | Name | Type | Mandatory| Description | | ------------- | ------------------- | ---- | ------------------------------------------------------------ | -| pdu | Array<number> | Yes | PDU, which is obtained from the received SMS message. | +| pdu | Array<number> | Yes | Protocol data unit, which is obtained from the received SMS message. | | specification | string | Yes | SMS protocol type.
- **3gpp**: GSM/UMTS/LTE SMS
- **3gpp2**: CDMA SMS| -**Return Value** +**Return value** | Type | Description | | -------------------------------------------- | --------------------------------- | @@ -61,7 +61,7 @@ Creates an SMS message instance based on the PDU and the specified SMS protocol. **Example** -``` +```js const specification = '3gpp'; // Display PDUs using numbers in an array, for example, [0x08, 0x91, ...]. const pdu = [0x08, 0x91]; @@ -87,11 +87,11 @@ Sends an SMS message. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [SendMessageOptions](#sendmessageoptions) | Yes | Options (including the callback) for sending an SMS message. For details, see [SendMessageOptions](#sendmessageoptions).| +| options | [SendMessageOptions](#sendmessageoptions) | Yes | Options (including the callback) for sending an SMS message.| **Example** -``` +```js let sendCallback = function (err, data) { console.log(`sendCallback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); } @@ -120,11 +120,11 @@ Obtains the default slot of the SIM card used to send SMS messages. This API use | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the result.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<number> | Yes | Callback used to return the result.
- **0**: card slot 1
- **1**: card slot 2| **Example** -``` +```js sms.getDefaultSmsSlotId((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -139,7 +139,7 @@ Obtains the default slot of the SIM card used to send SMS messages. This API use **System capability**: SystemCapability.Telephony.SmsMms -**Return Value** +**Return value** | Type | Description | | --------------- | ------------------------------------------------------------ | @@ -147,7 +147,7 @@ Obtains the default slot of the SIM card used to send SMS messages. This API use **Example** -``` +```js let promise = sms.getDefaultSmsSlotId(); promise.then(data => { console.log(`getDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`); @@ -156,6 +156,68 @@ promise.then(data => { }); ``` +## sms.setDefaultSmsSlotId7+ + +setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback<void>\): void + +Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +sms.setDefaultSmsSlotId(0,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.setDefaultSmsSlotId7+ + +setDefaultSmsSlotId\(slotId: number\): Promise<void> + +Sets the default slot of the SIM card used to send SMS messages. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let promise = sms.setDefaultSmsSlotId(0); +promise.then(data => { + console.log(`setDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setDefaultSmsSlotId fail, promise: err->${JSON.stringify(err)}`); +}); +``` ## sms.setSmscAddr7+ @@ -163,23 +225,23 @@ setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback\): Sets the short message service center (SMSC) address. This API uses an asynchronous callback to return the result. +This is a system API. + **Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms -This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------------------- | | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| smscAddr | string | Yes | SMSC address. | +| smscAddr | string | Yes | SMSC address. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** -``` +```js let slotId = 0; let smscAddr = '+861xxxxxxxxxx'; sms.setSmscAddr(slotId, smscAddr, (err,data) => { @@ -190,24 +252,24 @@ sms.setSmscAddr(slotId, smscAddr, (err,data) => { ## sms.setSmscAddr7+ -setSmscAddr\(slotId: number, smscAddr: string\): Promise +setSmscAddr\(slotId: number, smscAddr: string\): Promise\ Sets the SMSC address. This API uses a promise to return the result. +This is a system API. + **Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms -This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ----------------------------------------- | | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| smscAddr | string | Yes | SMSC address. | +| smscAddr | string | Yes | SMSC address. | -**Return Value** +**Return value** | Type | Description | | ------------------- | ------------------------------- | @@ -215,7 +277,7 @@ This is a system API and cannot be called by third-party applications. **Example** -``` +```js let slotId = 0; let smscAddr = '+861xxxxxxxxxx'; let promise = sms.setSmscAddr(slotId, smscAddr); @@ -233,12 +295,12 @@ getSmscAddr\(slotId: number, callback: AsyncCallback\): void Obtains the SMSC address. This API uses an asynchronous callback to return the result. +This is a system API. + **Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms -This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory| Description | @@ -248,7 +310,7 @@ This is a system API and cannot be called by third-party applications. **Example** -``` +```js let slotId = 0; sms.getSmscAddr(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -262,19 +324,19 @@ getSmscAddr\(slotId: number\): Promise Obtains the SMSC address. This API uses a promise to return the result. +This is a system API. + **Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) **System capability**: SystemCapability.Telephony.SmsMms -This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ----------------------------------------- | | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -**Return Value** +**Return value** | Type | Description | | --------------------- | --------------------------------------------- | @@ -282,7 +344,7 @@ This is a system API and cannot be called by third-party applications. **Example** -``` +```js let slotId = 0; let promise = sms.getSmscAddr(slotId); promise.then(data => { @@ -300,13 +362,13 @@ Checks whether the current device can send and receive SMS messages. This API wo **System capability**: SystemCapability.Telephony.SmsMms -**Return Value** +**Return value** | Type | Description | | ------- | ------------------------------------------------------------ | | boolean | - **true**: The device can send and receive SMS messages.
- **false**: The device cannot send or receive SMS messages.| -``` +```js let result = sms.hasSmsCapability(); console.log(`hasSmsCapability: ${JSON.stringify(result)}`); ``` @@ -319,13 +381,13 @@ Defines an SMS message instance. | Name | Type | Description | | ------------------------ | --------------------------------------- | ------------------------------------------------------------ | -| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: the path in which the device can reply to the SMS message through the originating SMSC.| +| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
TP-Reply-Path: The device returns a response based on the SMSC that sends the SMS message.| | isReplaceMessage | boolean | Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| | isSmsStatusReportMessage | boolean | Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| -| messageClass | [ShortMessageClass](#shortmessageclass) | SMS message type. | +| messageClass | [ShortMessageClass](#shortmessageclass) | Enumerates SMS message types. | | pdu | Array<number> | PDU in the SMS message. | -| protocolId | number | ID of the protocol used for sending SMS messages. | -| scAddress | string | Address of the short message service center (SMSC). | +| protocolId | number | Protocol identifier used for delivering the SMS message. | +| scAddress | string | SMSC address. | | scTimestamp | number | SMSC timestamp. | | status | number | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| | visibleMessageBody | string | SMS message body. | @@ -334,7 +396,7 @@ Defines an SMS message instance. ## ShortMessageClass -SMS message type. +Enumerates SMS message types. **System capability**: SystemCapability.Telephony.SmsMms @@ -374,12 +436,12 @@ Provides the callback for the SMS message sending result. It consists of three p | ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | | isLastPart | boolean | No | Whether this SMS message is the last part of a long SMS message. The value **true** indicates that this SMS message is the last part of a long SMS message, and value **false** indicates the opposite. The default value is **false**.| | result | [SendSmsResult](#sendsmsresult) | Yes | SMS message sending result. | -| url | string | Yes | URI for storing sent SMS messages. | +| url | string | Yes | URI for storing the sent SMS message. | ## IDeliveryShortMessageCallback -Provides the callback for the SMS message sending result. Return the SMS delivery report. +Provides the callback for the SMS message delivery report. **System capability**: SystemCapability.Telephony.SmsMms @@ -396,7 +458,7 @@ Enumerates SMS message sending results. | Name | Value | Description | | ------------------------------------ | ---- | ------------------------------------------------------ | -| SEND_SMS_SUCCESS | 0 | SMS message sent successfully. | -| SEND_SMS_FAILURE_UNKNOWN | 1 | Failed to send the SMS message due to unknown reasons. | +| SEND_SMS_SUCCESS | 0 | The SMS message is sent successfully. | +| SEND_SMS_FAILURE_UNKNOWN | 1 | Failed to send the SMS message due to an unknown reason. | | SEND_SMS_FAILURE_RADIO_OFF | 2 | Failed to send the SMS message because the modem is shut down. | | SEND_SMS_FAILURE_SERVICE_UNAVAILABLE | 3 | Failed to send the SMS message because the network is unavailable or SMS message sending or receiving is not supported.| diff --git a/en/application-dev/reference/apis/js-apis-statfs.md b/en/application-dev/reference/apis/js-apis-statfs.md index b2416b370967439456aa3d221dde5da992e6a49d..fc9109b25611afe452ea32255267b036e71a45b0 100644 --- a/en/application-dev/reference/apis/js-apis-statfs.md +++ b/en/application-dev/reference/apis/js-apis-statfs.md @@ -1,28 +1,15 @@ # statfs -> **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. +The statfs module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. -This module provides information related to the file system. It provides JS APIs to obtain the total number of bytes and the number of idle bytes of the file system. +> **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 statfs from '@ohos.statfs'; ``` - -## Guidelines - -Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). - -Application sandbox path of a file or directory = Application directory + File name or directory name - -For example, if the application directory obtained by using **getOrCreateLocalDir** is **dir** and the file name is **xxx.txt**, the application sandbox path of the file is as follows: - -```js -let path = dir + "xxx.txt"; -``` - ## statfs.getFreeBytes getFreeBytes(path:string):Promise<number> @@ -72,8 +59,12 @@ Obtains the number of free bytes of the specified file system in asynchronous mo - Example ```js - statfs.getFreeBytes(path, function(err, number){ - console.info("getFreeBytes callback successfully:"+ number); + import featureAbility from '@ohos.ability.featureAbility'; + let context = featureAbility.getContext(); + context.getFilesDir().then(function (path) { + statfs.getFreeBytes(path, function(err, number){ + console.info("Got free bytes successfully:"+ number); + }); }); ``` @@ -126,7 +117,11 @@ Obtains the total number of bytes of the specified file system in asynchronous m - Example ```js - statfs.getTotalBytes(path, function(err, number){ - console.info("getTotalBytes callback successfully:"+ number); + import featureAbility from '@ohos.ability.featureAbility'; + let context = featureAbility.getContext(); + context.getFilesDir().then(function (path) { + statfs.getTotalBytes(path, function(err, number){ + console.info("Got total bytes successfully:"+ number); + }); }); ``` 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 a0b973cb896a595e5361d5a441ab184bf0339b3d..093d6cb8b578e66b4213d2f247a95c7c0b9a8643 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -1,19 +1,19 @@ # 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. + > **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. > - API version 9 is a canary version for trial use. The APIs of this version may be unstable. -Obtains 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. - ## Modules to Import ```js -import storagestatistics from "@ohos.storageStatistics"; +import storageStatistics from "@ohos.storageStatistics"; ``` -## storagestatistics.getTotalSizeOfVolume +## storageStatistics.getTotalSizeOfVolume getTotalSizeOfVolume(volumeUuid: string): Promise<number> @@ -23,32 +23,34 @@ Asynchronously obtains the total size of the specified volume. This API uses a p **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | | volumeUuid | string | Yes | UUID of the volume.| -- Return value +**Return value** | Type | Description | | --------------------- | ---------------- | | Promise<number> | Promise used to return the total size of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getTotalSizeOfVolume(uuid).then(function(number){ + storageStatistics.getTotalSizeOfVolume(uuid).then(function(number){ console.info("getTotalSizeOfVolume successfully:"+ number); }).catch(function(err){ console.info("getTotalSizeOfVolume failed with error:"+ err); }); ``` -## storagestatistics.getTotalSizeOfVolume +## storageStatistics.getTotalSizeOfVolume getTotalSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void @@ -58,28 +60,28 @@ Asynchronously obtains the total size of the specified volume. This API uses a c **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | | volumeUuid | string | Yes | UUID of the volume. | | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getTotalSizeOfVolume(uuid, function(error, number){ + storageStatistics.getTotalSizeOfVolume(uuid, function(error, number){ // Do something. console.info("getTotalSizeOfVolume successfully:"+ number); }); ``` - - -## storagestatistics.getFreeSizeOfVolume +## storageStatistics.getFreeSizeOfVolume getFreeSizeOfVolume(volumeUuid: string): Promise<number> @@ -89,25 +91,27 @@ Asynchronously obtains the available space of the specified volume. This API use **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | | volumeUuid | string | Yes | UUID of the volume.| -- Return value +**Return value** | Type | Description | | --------------------- | ------------------ | | Promise<number> | Promise used to return the available space of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getFreeSizeOfVolume(uuid).then(function(number){ + storageStatistics.getFreeSizeOfVolume(uuid).then(function(number){ console.info("getFreeSizeOfVolume successfully:"+ number); }).catch(function(err){ console.info("getFreeSizeOfVolume failed with error:"+ err); @@ -115,7 +119,7 @@ Asynchronously obtains the available space of the specified volume. This API use ``` -## storagestatistics.getFreeSizeOfVolume +## storageStatistics.getFreeSizeOfVolume getFreeSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void @@ -125,26 +129,28 @@ Asynchronously obtains the available space of the specified volume. This API use **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | ---------------------------- | | volumeUuid | string | Yes | UUID of the volume. | | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getFreeSizeOfVolume(uuid, function(error, number){ + storageStatistics.getFreeSizeOfVolume(uuid, function(error, number){ // Do something. console.info("getFreeSizeOfVolume successfully:"+ number); }); ``` -## storagestatistics.getBundleStats9+ +## storageStatistics.getBundleStats9+ getBundleStats(packageName: string): Promise<BundleStats> @@ -154,32 +160,34 @@ Asynchronously obtains space information of an application. This API uses a prom **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | -------- | | packageName | string | Yes | Bundle name of the application.| - -- Return value + +**Return value** | Type | Description | | ------------------------------------------ | -------------------------- | | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| -- Example +**Example** ```js let packageName = ""; - storagestatistics.getBundleStats(packageName).then(function(BundleStats){ + storageStatistics.getBundleStats(packageName).then(function(BundleStats){ console.info("getBundleStats successfully:"+ JSON.stringify(BundleStats)); }).catch(function(err){ console.info("getBundleStats failed with error:"+ err); }); ``` -## storagestatistics.getBundleStats9+ +## storageStatistics.getBundleStats9+ getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>): void @@ -189,78 +197,80 @@ Asynchronously obtains space information of an application. This API uses a call **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | packageName | string | Yes | Bundle name of the application.| | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| - -- Example + +**Example** ```js let packageName = ""; - storagestatistics.getBundleStats(packageName, function(error, BundleStats){ + storageStatistics.getBundleStats(packageName, function(error, BundleStats){ // Do something. console.info("getBundleStats successfully:"+ JSON.stringify(BundleStats)); }); ``` +## storageStatistics.getCurrentBundleStats9+ - -## storagestatistics.getCurrentBundleStats9+ - -getCurrentBundleStats(): Promise +getCurrentBundleStats(): Promise<BundleStats> Asynchronously obtains space information of the current third-party application. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Return value +**Return value** | Type | Description | | ------------------------------------------ | -------------------------- | | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | -- Example +**Example** ```js - let bundleStats = await storageStatistics.getCurrentBundleStats(); - console.info("getCurrentBundleStats successfully:"+ JSON.stringify(bundleStats)); + let bundleStats = storageStatistics.getCurrentBundleStats(); + console.info("getCurrentBundleStats successfully:"+ JSON.stringify(bundleStats)); ``` -## storagestatistics.getCurrentBundleStats9+ +## storageStatistics.getCurrentBundleStats9+ -getCurrentBundleStats(callback: AsyncCallback): void +getCurrentBundleStats(callback: AsyncCallback<BundleStats>): void Asynchronously obtains space information of the current third-party application. This API uses a callback to return the result. **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Parameters +**Parameters** | Name | Type | Mandatory | Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | -- Example +**Example** ```js - storagestatistics.getCurrentBundleStats(function(error, bundleStats){ + storageStatistics.getCurrentBundleStats(function(error, bundleStats){ // Do something. console.info("getCurrentBundleStats successfully:"+ JSON.stringify(bundleStats)); }); ``` - - - + ## BundleStats9+ **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Attributes + +This is a system API and cannot be called by third-party applications. + + +### Attributes | Name | Type | Description | | --------- | ------ | -------------- | @@ -269,11 +279,9 @@ Asynchronously obtains space information of the current third-party application. | dataSize | number | Total data size of the application.| +## storageStatistics.getTotalSize9+ - -## storagestatistics.getTotalSize9+ - -getTotalSize(): Promise +getTotalSize(): Promise<number> Obtains the total space of the built-in memory card. This API uses a promise to return the result. @@ -281,24 +289,26 @@ Obtains the total space of the built-in memory card. This API uses a promise to **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Return value +This is a system API and cannot be called by third-party applications. + + +**Return value** | Type | Description | | --------------------- | ------------------ | | Promise<number> | Promise used to return the total space of the built-in memory card. | -- Example +**Example** ```js - let number = await storageStatistics.getTotalSize(); - console.info("getTotalSize successfully:"+ JSON.stringify(number)); + let number = storageStatistics.getTotalSize(); + console.info("getTotalSize successfully:"+ JSON.stringify(number)); ``` - -## storagestatistics.getTotalSize9+ -getTotalSize(callback: AsyncCallback): void +## storageStatistics.getTotalSize9+ + +getTotalSize(callback: AsyncCallback<number>): void Obtains the total space of the built-in memory card. This API uses a callback to return the result. @@ -306,27 +316,29 @@ Obtains the total space of the built-in memory card. This API uses a callback to **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory | Description | | -------- | ------------------------------------ | ---- | ------------------------ | | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| -- Example +**Example** ```js - storagestatistics.getTotalSize(function(error, number){ + storageStatistics.getTotalSize(function(error, number){ // Do something. console.info("getTotalSize successfully:"+ JSON.stringify(number)); }); ``` -## storagestatistics.getFreeSize9+ +## storageStatistics.getFreeSize9+ -getFreeSize(): Promise +getFreeSize(): Promise<number> Obtains the available space of the built-in memory card. This API uses a promise to return the result. @@ -334,25 +346,27 @@ Obtains the available space of the built-in memory card. This API uses a promise **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Return value +This is a system API and cannot be called by third-party applications. + + +**Return value** | Type | Description | | --------------------- | ------------------ | | Promise<number> | Promise used to return the available space of the built-in memory card.| -- Example +**Example** ```js - let number = await storageStatistics.getFreeSize(); - console.info("getFreeSize successfully:"+ JSON.stringify(number)); + let number = storageStatistics.getFreeSize(); + console.info("getFreeSize successfully:"+ JSON.stringify(number)); ``` -## storagestatistics.getFreeSize9+ +## storageStatistics.getFreeSize9+ -getFreeSize(callback: AsyncCallback): void +getFreeSize(callback: AsyncCallback<number>): void Obtains the available space of the built-in memory card. This API uses a callback to return the result. @@ -360,26 +374,26 @@ Obtains the available space of the built-in memory card. This API uses a callbac **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------- | | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| -- Example +**Example** ```js - storagestatistics.getFreeSize(function(error, number){ + storageStatistics.getFreeSize(function(error, number){ // Do something. console.info("getFreeSize successfully:"+ JSON.stringify(number)); }); ``` - - -## storagestatistics.getSystemSize9+ +## storageStatistics.getSystemSize9+ getSystemSize(): Promise<number> @@ -389,25 +403,27 @@ Asynchronously obtains the system space. This API uses a promise to return the r **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Return value +This is a system API and cannot be called by third-party applications. + + +**Return value** | Type | Description | | --------------------- | ---------------- | | Promise<number> | Promise used to return the system space obtained.| -- Example +**Example** ```js - storagestatistics.getSystemSize().then(function(number){ + storageStatistics.getSystemSize().then(function(number){ console.info("getSystemSize successfully:"+ number); }).catch(function(err){ console.info("getSystemSize failed with error:"+ err); }); ``` -## storagestatistics.getSystemSize9+ +## storageStatistics.getSystemSize9+ getSystemSize(callback:AsyncCallback<number>):void @@ -417,28 +433,28 @@ Asynchronously obtains the system space. This API uses a callback to return the **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | | callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| -- Example +**Example** ```js - storagestatistics.getSystemSize(function(error, number){ + storageStatistics.getSystemSize(function(error, number){ // Do something. console.info("getSystemSize successfully:"+ number); }); ``` - - - -## storagestatistics.getUserStorageStats9+ -getUserStorageStats(userId?: string): Promise<StorageStats> +## storageStatistics.getUserStorageStats9+ + +getUserStorageStats(userId? : number): Promise<StorageStats> Asynchronously obtains the space occupied by each type of user data. This API uses a promise to return the result. @@ -446,34 +462,36 @@ Asynchronously obtains the space occupied by each type of user data. This API us **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | - | userId | string | No | User ID.
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| + | userId | string | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| -- Return value +**Return value** | Type | Description | | --------------------- | ---------------- | | Promise<[StorageStats](#StorageStats)> | Promise used to return the information obtained.| -- Example +**Example** ```js let userId = ""; - storagestatistics.getUserStorageStats(userId).then(function(StorageStats){ + storageStatistics.getUserStorageStats(userId).then(function(StorageStats){ console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); }).catch(function(err){ console.info("getUserStorageStats failed with error:"+ err); }); ``` -## storagestatistics.getUserStorageStats9+ +## storageStatistics.getUserStorageStats9+ -getUserStorageStats(userId?: string, callback:AsyncCallback<StorageStats>):void +getUserStorageStats(userId: number, callback:AsyncCallback<StorageStats>):void Asynchronously obtains the space occupied by each type of user data. This API uses a callback to return the result. @@ -481,31 +499,37 @@ Asynchronously obtains the space occupied by each type of user data. This API us **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -**System API**: This is a system API and cannot be called by third-party applications. -- Parameters +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | - | userId | string | No | User ID.
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | + | userId | string | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| -- Example +**Example** ```js - storagestatistics.getUserStorageStats(userId, function(error, StorageStats){ + let userId = ""; + storageStatistics.getUserStorageStats(userId, function(error, StorageStats){ // Do something. console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); }); ``` - ## StorageStats9+ **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Attributes + +This is a system API and cannot be called by third-party applications. + + +### Attributes | Name | Type | Description | | --------- | ------ | -------------- | diff --git a/en/application-dev/reference/apis/js-apis-system-bluetooth.md b/en/application-dev/reference/apis/js-apis-system-bluetooth.md index 9f2ef61d8465f220a97884f3097c43b203e07b80..a8c77cd86a20c0401d01ce1e54a61c58c7aace17 100644 --- a/en/application-dev/reference/apis/js-apis-system-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-system-bluetooth.md @@ -37,6 +37,7 @@ Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes sys ``` bluetooth.startBLEScan({ + interval:0, success() { console.log('call bluetooth.startBLEScan success.'); }, @@ -71,7 +72,6 @@ Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLE ``` bluetooth.stopBLEScan({ - interval:0, success() { console.log('call bluetooth.stopBLEScan success.'); }, @@ -120,19 +120,12 @@ Subscribes to the newly detected BLE device. If this API is called multiple time **Example** ``` - bluetooth.startBLEScan({ - success() { - bluetooth.subscribeBLEFound({ - success(data) { - const [device] = data.devices; - if (!!device) { - bluetooth.stopBLEScan(); - } - } - }); + bluetooth.subscribeBLEFound({ + success(data) { + console.log('Called bluetooth.subscribeBLEFound successsully, data: ${data}.'); }, - fail(code, data) { - console.log('Failed to start BLE device scan, code: ${code}, data: ${data}'); + fail(data, code) { + console.log('Failed to call bluetooth.startBLEScan, data: ${data}, code: ${code}.'); } }); ``` 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 c4f862b0e3cbf448631be452f826ac395a44435c..cd4100d455e6f47f6d2600562a4d0522c885284a 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -50,7 +50,7 @@ export default { '+Enz0RzmVFh/4yk6lmqRzuEFQqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBw\n' + 'jBpApTJ3TeneOo6Z5QIDAQAB', success: function(data) { - console.log(`handling successful:${data.text}`); + console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); @@ -83,7 +83,7 @@ export default { 'M9TORIgdH8MjIbWsGnndAkEAw9yURDaorE8IYPLF2IEn09g1uzvWPs3phDb6smVx\n' + '8GfqIdUNf+aCG5TZK/kXBF1sqcsi7jXMAf4jBlejVbSVZg==', success: function(data) { - console.log(`handling successful:${data.text}`); + console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); @@ -130,13 +130,13 @@ export default { action: 'encrypt', // Text to be encrypted. text: 'hello', - // Base64-encoded key used for encryption. + // Base64-encoded key. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: '0', ivLen: '16', success: function(data) { - console.log(`handling successful:${data.text}`); + console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); @@ -150,13 +150,13 @@ export default { action: 'decrypt', // Text to be decrypted, which is binary text encoded in Base64. text: '1o0kf2HXwLxHkSh5W5NhzA==', - // Base64-encoded key used for decryption. + // Base64-encoded key. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: '0', ivLen: '16', success: function(data) { - console.log(`handling success:${data.text}`); + console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { console.log(`### Failed to decrypt cipher.rsa ### ${code}:${data}`); diff --git a/en/application-dev/reference/apis/js-apis-system-file.md b/en/application-dev/reference/apis/js-apis-system-file.md index f05357dbe766366e8653c51b85544d12317385ce..841f0b90056e377710f20336a3a5bf07ba58dde8 100644 --- a/en/application-dev/reference/apis/js-apis-system-file.md +++ b/en/application-dev/reference/apis/js-apis-system-file.md @@ -1,9 +1,7 @@ # File Storage - - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.fileio`](js-apis-fileio.md) instead. +> **NOTE**
+> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.fileio`](js-apis-fileio.md). > > - 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. @@ -26,21 +24,21 @@ Moves a specified file to a given location. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| srcUri | string | Yes | URI of the file to move. | -| dstUri | string | Yes | URI of the location to which the file is to move. | -| success | Function | No | Called when the source file is moved to the specified location successfully. This function returns the URI of the destination location. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| srcUri | string | Yes| Uniform resource identifier (URI) of the file to move.
The URI can contain a maximum of 128 characters, excluding the following characters: "\*+,:;<=>?[]\|\x7F | +| dstUri | string | Yes| URI of the location to which the file is to move.
The URI can contain a maximum of 128 characters, excluding the following characters: "\*+,:;<=>?[]\|\x7F | +| success | Function | No| Called when the file is moved to the specified location. This API returns the URI of the destination location.| +| fail | Function | No| Called when the file fails to be moved.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -66,27 +64,27 @@ export default { copy(Object): void -Copies a file and saves the copy to a specified location. +Copies a file to the given URI. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| srcUri | string | Yes | URI of the file to copy. | -| dstUri | string | Yes | URI of the location to which the copy is to save.
The directory of application resources and URI of the **tmp** type are not supported. | -| success | Function | No | Called when the source file is copied and saved to the specified location successfully. This function returns the URI of the destination location. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| srcUri | string | Yes| URI of the file to copy.| +| dstUri | string | Yes| URI of the location to which the copy is to be saved.
The directory of application resources and URI of the **tmp** type are not supported.| +| success | Function | No| Called when the file is copied and saved to the specified location. This API returns the URI of the destination location.| +| fail | Function | No| Called when the file fails to be copied.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -112,41 +110,41 @@ export default { list(Object): void -Obtains the list of all files in a specified directory. +Obtains all files in the specified directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory.
The URI can contain a maximum of 128 characters, excluding the following characters: "\*+,:;<=>?[]\|\x7F | +| success | Function | No| Called when the file list is obtained.| +| fail | Function | No| Called when the file list fails to be obtained.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| fileList | Array<FileInfo> | File list. The format of each file is as follows:
{
uri:'file1',
lastModifiedTime:1589965924479,
length:10240,
type: 'file'
} | +| fileList | Array<FileInfo> | File list. The format of each file is as follows:
{
uri:'file1',
lastModifiedTime:1589965924479,
length:10240,
type: 'file'
} | -**Table1** FileInfo +**Table 1** FileInfo -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| uri | string | File URI. | -| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | -| length | number | File size, in bytes. | -| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | +| uri | string | URI of the file.| +| lastModifiedTime | number | Timestamp when the file is saved the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT.| +| length | number | File size, in bytes.| +| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -156,7 +154,7 @@ export default { file.list({ uri: 'internal://app/pic', success: function(data) { - console.log(data.fileList); + console.log(JSON.stringify(data.fileList)); }, fail: function(data, code) { console.error('call fail callback fail, code: ' + code + ', data: ' + data); @@ -171,37 +169,37 @@ export default { get(Object): void -Obtains information about a specified local file. +Obtains information about a local file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | File URI. | -| recursive | boolean | No | Whether to recursively obtain the file list under a subdirectory. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the file.| +| recursive | boolean | No| Whether to recursively obtain the file list under a subdirectory. The default value is **false**.| +| success | Function | No| Called when the file information is obtained.| +| fail | Function | No| Called when the file information fails to be obtained.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| uri | string | File URI. | -| length | number | File size, in bytes. | -| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | -| type | string | File type. The values are as follows:
- **dir**: directory
- **file**: file | -| subFiles | Array | File list. | +| uri | string | URI of the file.| +| length | number | File size, in bytes.| +| lastModifiedTime | number | Timestamp when the file is saved the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT.| +| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | +| subFiles | Array | List of files.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -226,26 +224,26 @@ export default { delete(Object): void -Deletes local files. +Deletes a local file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the file to delete, which cannot be an application resource path. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the file to delete. It cannot be an application resource path.| +| success | Function | No| Called when the file is deleted.| +| fail | Function | No| Called when the file fails to be deleted.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Incorrect parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -270,28 +268,28 @@ export default { writeText(Object): void -Writes text into a specified file. +Writes text into a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | -| text | string | Yes | Character string to write into the local file. | -| encoding | string | No | Encoding format. The default format is UTF-8. | -| append | boolean | No | Whether to enable the append mode. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file. If it does not exist, a file will be created.| +| text | string | Yes| Text to write into the file. | +| encoding | string | No| Encoding format. The default format is **UTF-8**.| +| append | boolean | No| Whether to enable the append mode. The default value is **false**.| +| success | Function | No| Called when the text is written into the specified file.| +| fail | Function | No| Called when the text fails to be written into the file.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Incorrect parameter. | -| 300 | I/O error. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| **Example** @@ -317,28 +315,28 @@ export default { writeArrayBuffer(Object): void -Writes buffer data into a specified file. +Writes buffer data into a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | -| buffer | Uint8Array | Yes | Buffer from which the data is derived. | -| position | number | No | Offset to the position where the writing starts. The default value is **0**. | -| append | boolean | No | Whether to enable the append mode. The default value is **false**. If the value is **true**, the **position** parameter will become invalid. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file. If it does not exist, a file will be created.| +| buffer | Uint8Array | Yes| Buffer from which the data is derived.| +| position | number | No| Offset to the position where the writing starts. The default value is **0**.| +| append | boolean | No| Whether to enable the append mode. The default value is **false**. If the value is **true**, the **position** parameter will become invalid.| +| success | Function | No| Called when buffer data is written into the file. | +| fail | Function | No| Called when buffer data fails to be written into the file.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| **Example** @@ -347,7 +345,7 @@ export default { writeArrayBuffer() { file.writeArrayBuffer({ uri: 'internal://app/test', - buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. + buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. success: function() { console.log('call writeArrayBuffer success.'); }, @@ -364,36 +362,36 @@ export default { readText(Object): void -Reads text from a specified file. +Reads text from a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. | -| encoding | string | No | Encoding format. The default format is UTF-8. | -| position | number | No | Position where the reading starts. The default value is the start position of the file. | -| length | number | No | Length of the text to be read (in bytes). The default value is **4096**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file.| +| encoding | string | No| Encoding format. The default format is **UTF-8**.| +| position | number | No| Position where the reading starts. The default value is the start position of the file.| +| length | number | No| Length of the text to read, in bytes. The default value is **4096**.| +| success | Function | No| Called when the text is read successfully.| +| fail | Function | No| Called when the text failed to be read.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| text | string | Text read from the specified file. | +| text | string | Text read from the specified file.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | The file or directory does not exist. | -| 302 | The size of text to read exceeds 4096 bytes. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| +| 302 | The text to read exceeds 4 KB.| **Example** @@ -418,34 +416,34 @@ export default { readArrayBuffer(Object): void -Reads buffer data from a specified file. +Reads buffer data from a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. | -| position | number | No | Position where the reading starts. The default value is the start position of the file. | -| length | number | No | Length of data to read. If this parameter is not set, the reading proceeds until the end of the file. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file.| +| position | number | No| Position where the reading starts. The default value is the start position of the file.| +| length | number | No| Length of data to read. If this parameter is not set, the reading proceeds until the end of the file.| +| success | Function | No| Called when the buffer data is read successfully.| +| fail | Function | No| Called when the buffer data fails to be read.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| buffer | Uint8Array | File content that is read | +| buffer | Uint8Array | Data read.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -472,26 +470,26 @@ export default { access(Object): void -Checks whether a specified file or directory exists. +Checks whether a file or directory exists. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory or file. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory or file to check.| +| success | Function | No| Called when the operation is successful.| +| fail | Function | No| Called when the operation fails.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -516,26 +514,26 @@ export default { mkdir(Object): void -Creates a specified directory. +Creates a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory. | -| recursive | boolean | No | Whether to recursively create upper-level directories of the specified directory. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory to create.| +| recursive | boolean | No| Whether to recursively create upper-level directories of the specified directory. The default value is **false**.| +| success | Function | No| Called when the directory is created.| +| fail | Function | No| Called when the directory fails to be created.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| **Example** @@ -560,27 +558,27 @@ export default { rmdir(Object): void -Deletes a specified directory. +Deletes a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory. | -| recursive | boolean | No | Whether to recursively delete subfiles and subdirectories of the specified directory. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory to delete.| +| recursive | boolean | No| Whether to recursively delete files and subdirectories of the specified directory. The default value is **false**.| +| success | Function | No| Called when the directory is deleted.| +| fail | Function | No| Called when the directory fails to be deleted.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +**Return value of fail()** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -598,4 +596,4 @@ export default { }); } } -``` \ No newline at end of file +``` 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 b6bdef1d34b9f544e1380d3d4a9a7cd7d1d293b7..309e32bdae7af66c7ca14802f734ccca0ccdbb99 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -6,7 +6,7 @@ ## Modules to Import -``` +```js import data from '@ohos.telephony.data'; ``` @@ -14,7 +14,7 @@ import data from '@ohos.telephony.data'; getDefaultCellularDataSlotId(callback: AsyncCallback\): void -Obtains the default SIM card used for mobile data. This API uses an asynchronous callback to return the result. +Obtains the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -28,7 +28,7 @@ Obtains the default SIM card used for mobile data. This API uses an asynchronous **Example** -``` +```js data.getDefaultCellularDataSlotId((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -38,13 +38,13 @@ data.getDefaultCellularDataSlotId((err, data) => { getDefaultCellularDataSlotId(): Promise\ -Obtains the default SIM card used for mobile data. This API uses a promise to return the result. +Obtains the default slot of the SIM card used for mobile data. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Telephony.CellularData -**Return Value** +**Return value** | Type | Description | | ----------------- | ------------------------------------------------------------ | @@ -52,12 +52,74 @@ Obtains the default SIM card used for mobile data. This API uses a promise to re **Example** -``` +```js let promise = data.getDefaultCellularDataSlotId(); promise.then((data) => { - console.log(`test success, promise: data->${JSON.stringify(data)}`); + console.log(`getDefaultCellularDataSlotId success, promise: data->${JSON.stringify(data)}`); }).catch((err) => { - console.error(`test fail, promise: err->${JSON.stringify(err)}`); + console.error(`getDefaultCellularDataSlotId fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## data.setDefaultCellularDataSlotId + +setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void + +Sets the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object. | + +**Example** + +```js +data.setDefaultCellularDataSlotId(0,(err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.setDefaultCellularDataSlotId + +setDefaultCellularDataSlotId(slotId: number): Promise\ + +Sets the default slot of the SIM card used for mobile data. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------- | +| Promise<\void\> | Promise that returns no value. | + +**Example** + +```js +let promise = data.setDefaultCellularDataSlotId(0); +promise.then((data) => { + console.log(`setDefaultCellularDataSlotId success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`setDefaultCellularDataSlotId fail, promise: err->${JSON.stringify(err)}`); }); ``` @@ -77,7 +139,7 @@ Obtains the cellular data flow type, which can be uplink or downlink. This API u **Example** -``` +```js data.getCellularDataFlowType((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -91,7 +153,7 @@ Obtains the cellular data flow type, which can be uplink or downlink. This API u **System capability**: SystemCapability.Telephony.CellularData -**Return Value** +**Return value** | Type | Description | | ---------------------------------------- | ----------------------------------------------- | @@ -99,7 +161,7 @@ Obtains the cellular data flow type, which can be uplink or downlink. This API u **Example** -``` +```js let promise = data.getCellularDataFlowType(); promise.then((data) => { console.log(`test success, promise: data->${JSON.stringify(data)}`); @@ -124,7 +186,7 @@ Obtains the connection status of the packet switched (PS) domain. This API uses **Example** -``` +```js data.getCellularDataState((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -138,7 +200,7 @@ Obtains the connection status of the PS domain. This API uses a promise to retur **System capability**: SystemCapability.Telephony.CellularData -**Return Value** +**Return value** | Type | Description | | ------------------------------------------------ | ------------------------------------- | @@ -146,7 +208,7 @@ Obtains the connection status of the PS domain. This API uses a promise to retur **Example** -``` +```js let promise = data.getCellularDataState(); promise.then((data) => { console.log(`test success, promise: data->${JSON.stringify(data)}`); @@ -169,11 +231,11 @@ Checks whether the cellular data service is enabled. This API uses an asynchrono | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: The cellular data service is enabled.
**false**: The cellular data service is disabled.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: The cellular data service is enabled.
- **false**: The cellular data service is disabled.| **Example** -``` +```js data.isCellularDataEnabled((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -189,15 +251,15 @@ Checks whether the cellular data service is enabled. This API uses a promise to **System capability**: SystemCapability.Telephony.CellularData -**Return Value** +**Return value** | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
**true**: The cellular data service is enabled.
**false**: The cellular data service is disabled.| +| Promise\ | Promise used to return the result.
- **true**: The cellular data service is enabled.
- **false**: The cellular data service is disabled.| **Example** -``` +```js let promise = data.isCellularDataEnabled(); promise.then((data) => { console.log(`test success, promise: data->${JSON.stringify(data)}`); @@ -220,12 +282,12 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: Roaming is enabled for the cellular data service.
**false**: Roaming is disabled for the cellular data service.| +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2 | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: Roaming is enabled for the cellular data service.
- **false**: Roaming is disabled for the cellular data service.| **Example** -``` +```js data.isCellularDataRoamingEnabled(0,(err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -245,17 +307,17 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| -**Return Value** +**Return value** | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
**true**: Roaming is enabled for the cellular data service.
**false**: Roaming is disabled for the cellular data service.| +| Promise\ | Promise used to return the result.
- **true**: Roaming is enabled for the cellular data service.
- **false**: Roaming is disabled for the cellular data service.| **Example** -``` +```js let promise = data.isCellularDataRoamingEnabled(0); promise.then((data) => { console.log(`test success, promise: data->${JSON.stringify(data)}`); @@ -275,7 +337,7 @@ Defines the cellular data flow type. | DATA_FLOW_TYPE_NONE | 0 | No uplink or downlink data is available. | | DATA_FLOW_TYPE_DOWN | 1 | Only the downlink data is available. | | DATA_FLOW_TYPE_UP | 2 | Only the uplink data is available. | -| DATA_FLOW_TYPE_UP_DOWN | 3 | Both uplink data and downlink data are available. | +| DATA_FLOW_TYPE_UP_DOWN | 3 | Both the uplink data and downlink data are available. | | DATA_FLOW_TYPE_DORMANT | 4 | No uplink or downlink data is available because the lower-layer link is in the dormant state.| ## DataConnectState @@ -286,7 +348,7 @@ Describes the connection status of a cellular data link. | Name | Value | Description | | ----------------------- | ---- | -------------------------- | -| DATA_STATE_UNKNOWN | -1 | The status of the cellular data link is unknown. | +| DATA_STATE_UNKNOWN | -1 | The status of the cellular data link is unknown. | | DATA_STATE_DISCONNECTED | 0 | The cellular data link is disconnected. | | DATA_STATE_CONNECTING | 1 | The cellular data link is being connected.| | DATA_STATE_CONNECTED | 2 | The cellular data link is connected. | diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md index 39333510193d27d613ba48896e58f2d1dd3434f5..a91577d272d67835ba1d7194200be508ed44a6ea 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-volumemanager.md @@ -1,13 +1,13 @@ # Volume Management +The volumeManager module provides APIs for volume and disk management, including obtaining volume information, mounting or unmounting volumes, partitioning disks, and formatting volumes. + > **NOTE**
> > - The initial APIs of this module are supported since API version 9. > - API version 9 is a canary version for trial use. The APIs of this version may be unstable. > - The APIs of this module are system APIs and cannot be called by third-party applications. -The APIs of this module can be used to perform volume and disk management, including obtaining volume information, mounting and unmounting volumes, partitioning disks, and formatting volumes. - ## Modules to Import ```js @@ -20,19 +20,21 @@ getAllVolumes(): Promise<Array<Volume>> Asynchronously obtains information about all available volumes. This API uses a promise to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Return value +**Return value** | Type | Description | | ---------------------------------- | -------------------------- | | Promise<[Volume](#volume)[]> | Promise used to return the execution result.| -- Example +**Example** ```js volumemanager.getAllVolumes().then(function(volumes){ - // do something + // Do something. }); ``` @@ -42,20 +44,22 @@ getAllVolumes(callback: AsyncCallback<Array<Volume>>): void Asynchronously obtains information about all available volumes. This API uses a callback to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | | callback | callback:AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| - -- Example + +**Example** ```js let uuid = ""; - volumemanager.getAllVolumes(uuid, function(error, volumes){ - // do something + volumemanager.getAllVolumes(function(error, volumes){ + // Do something }); ``` @@ -66,26 +70,28 @@ mount(volumeId: string): Promise<boolean> Asynchronously mounts a volume. This API uses a promise to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description| | -------- | ------ | ---- | ---- | | volumeId | string | Yes | Volume ID.| -- Return value +**Return value** | Type | Description | | ---------------------- | ---------- | | Promise<boolean> | Promise used to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.mount(volumeId).then(function(flag){ - // do something + // Do something }); ``` @@ -95,21 +101,23 @@ mount(volumeId: string, callback:AsyncCallback<boolean>):void Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.mount(volumeId, function(error, flag){ - // do something + // Do something }); ``` @@ -119,26 +127,28 @@ unmount(volumeId: string): Promise<boolean> Asynchronously unmounts a volume. This API uses a promise to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description| | -------- | ------ | ---- | ---- | | volumeId | string | Yes | Volume ID.| -- Return value +**Return value** | Type | Description | | ---------------------- | ---------- | | Promise<boolean> | Promise used to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.unmount(volumeId).then(function(flag){ - // do something + // Do something }); ``` @@ -148,21 +158,306 @@ unmount(volumeId: string, callback:AsyncCallback<boolean>):void Asynchronously unmounts a volume. This API uses a callback to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.unmount(volumeId, function(error, flag){ - // do something + // Do something + }); + ``` + +## volumemanager.getVolumeByUuid + +getVolumeByUuid(uuid: string): Promise<Volume> + +Asynchronously obtains volume information based on the universally unique identifier (UUID). This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| + +**Return value** + + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + +**Example** + + ```js + let uuid = ""; + let volume = await volumemanager.getVolumeByUuid(uuid); + ``` + +## volumemanager.getVolumeByUuid + +getVolumeByUuid(uuid: string, callback: AsyncCallback<Volume>): void + +Asynchronously obtains volume information based on the UUID. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------------------ | ---- | -------------------- | + | uuid | string | Yes | UUID of the volume. | + | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + +**Example** + + ```js + let uuid = ""; + volumemanager.getVolumeByUuid(uuid, (error, volume) => { + // Do something. + }); + ``` + +## volumemanager.getVolumeById + +getVolumeById(id: string): Promise<Volume> + +Asynchronously obtains volume information based on the volume ID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory | Description| + | -------- | ------ | ---- | ---- | + | id | string | Yes | Volume ID.| + +**Return value** + + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + +**Example** + + ```js + let id = ""; + let volume = await volumemanager.getVolumeById(id); + ``` + +## volumemanager.getVolumeById + +getVolumeById(id: string, callback: AsyncCallback<Volume>): void + +Asynchronously obtains volume information based on the volume ID. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------------------ | ---- | -------------------- | + | id | string | Yes | Volume ID. | + | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + +**Example** + + ```js + let id = ""; + volumemanager.getVolumeById(id, (error, volume) => { + // Do something. + }); + ``` + +## volumemanager.setVolumeDescription + +setVolumeDescription(uuid: string, description: string): Promise<void> + +Asynchronously sets the volume description based on the UUID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | --------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| + | description | string | Yes | Volume description.| + +**Return value** + + | Type | Description | + | ---------------------- | -------------------------- | + | Promise<void> | Promise used to return the result. | + +**Example** + + ```js + let uuid = ""; + let description = ""; + let bool = await volumemanager.setVolumeDescription(uuid, description); + ``` + +## volumemanager.setVolumeDescription + +setVolumeDescription(uuid: string, description: string, callback: AsyncCallback<void>): void + +Asynchronously sets the volume description based on the UUID. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | --------------------------------------- | ---- | ---------------- | + | uuid | string | Yes | UUID of the volume. | + | description | string | Yes | Volume description. | + | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + + ```js + let uuid = ""; + let description = ""; + volumemanager.setVolumeDescription(uuid, description, (error, bool) => { + // Do something. + }); + ``` + +## volumemanager.format + +format(volId: string): Promise<void> + +Asynchronously formats a volume. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | volId | string | Yes | Volume ID.| + +**Return value** + + | Type | Description | + | --------------------- | ----------------------- | + | Promise<void> | Promise used to return the result. | + +**Example** + + ```js + let volId = ""; + let bool = await volumemanager.format(volId); + ``` + +## volumemanager.format + +format(volId: string, callback: AsyncCallback<void>): void + +Asynchronously formats a volume. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | --------------------------------------- | ---- | ---------------- | + | volId | string | Yes | Volume ID. | + | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + + ```js + let volId = ""; + volumemanager.format(volId, (error, bool) => { + // Do something. + }); + ``` + +## volumemanager.partition + +partition(volId: string, fstype: string): Promise<void> + +Asynchronously partitions a disk. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | volId | string | Yes | ID of the disk to which the volume belongs.| + | fstype | string | Yes | Partition type. | + +**Return value** + + | Type | Description | + | --------------------- | ----------------------- | + | Promise<void> | Promise used to return the result. | + +**Example** + + ```js + let volId = ""; + let fstype = ""; + let bool = await volumemanager.partition(volId, fstype); + ``` + +## volumemanager.partition + +partition(volId: string, fstype : string, callback: AsyncCallback<void>): void + +Asynchronously partitions a disk. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | --------------------------------------- | ---- | ---------------- | + | volId | string | Yes | ID of the disk to which the volume belongs. | + | fstype | string | Yes | Partition type. | + | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + + ```js + let volId = ""; + let fstype = ""; + volumemanager.format(volId, fstype, (error, bool) => { + // Do something. }); ``` @@ -172,11 +467,11 @@ Asynchronously unmounts a volume. This API uses a callback to return the result. ### Attributes -| Name | Type | Description | +| Name | Type | Description | | ----------- | ------- | -------------------- | -| id | number | Volume ID. | -| uuid | string | Universally unique identifier (UUID) of the volume. | +| id | string | Volume ID. | +| uuid | string | UUID of the volume. | | description | string | Description of the volume. | -| removable | boolean | Whether the volume is a removable storage device.| -| state | int | Current volume status. | +| removable | boolean | Whether the volume is a removable storage device.| +| state | number | Volume state. | | path | string | Mount address of the volume. | diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index bf13c3d9188fe48996c9f56342af8436bb398b9e..e71562765f7b0a4330cfce26a8c57f835f8ed055 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -426,7 +426,7 @@ WebGLRenderingContextBase | CONTEXT_LOST_WEBGL | GLenum | Yes| | UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| | BROWSER_DEFAULT_WEBGL | GLenum | Yes| -| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| +| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| | drawingBufferWidth | GLsizei | Yes| | drawingBufferHeight | GLsizei | Yes| @@ -435,124 +435,124 @@ WebGLRenderingContextBase | Method| Return Value Type| | -------- | -------- | -| getContextAttributes() | WebGLContextAttributes \| null | +| getContextAttributes() | WebGLContextAttributes \| null | | isContextLost() | boolean | -| getSupportedExtensions() | string[] \| null | -| getExtension(name: string) | any | -| activeTexture(texture: GLenum) | void | -| attachShader(program: WebGLProgram, shader: WebGLShader) | void | -| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | -| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | -| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | -| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | -| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| blendEquation(mode: GLenum) | void | -| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | -| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | -| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | -| checkFramebufferStatus(target: GLenum) | GLenum | -| clear(mask: GLbitfield) | void | -| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| clearDepth(depth: GLclampf) | void | -| clearStencil(s: GLint) | void | -| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | -| compileShader(shader: WebGLShader) | void | -| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | -| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| createBuffer() | WebGLBuffer \| null | -| createFramebuffer() | WebGLFramebuffer \| null | -| createProgram() | WebGLProgram \| null | -| createRenderbuffer() | WebGLRenderbuffer \| null | -| createShader(type: GLenum) | WebGLShader \| null | -| createTexture() | WebGLTexture \| null | -| cullFace(mode: GLenum) | void | -| deleteBuffer(buffer: WebGLBuffer \| null) | void | -| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | -| deleteProgram(program: WebGLProgram \| null) | void | -| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | -| deleteShader(shader: WebGLShader \| null) | void | -| deleteTexture(texture: WebGLTexture \| null) | void | -| depthFunc(func: GLenum) | void | -| depthMask(flag: GLboolean) | void | -| depthRange(zNear: GLclampf, zFar: GLclampf) | void | -| detachShader(program: WebGLProgram, shader: WebGLShader) | void | -| disable(cap: GLenum) | void | -| disableVertexAttribArray(index: GLuint) | void | -| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | -| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| enable(cap: GLenum) | void | -| enableVertexAttribArray(index: GLuint) | void | +| getSupportedExtensions() | string[] \| null | +| getExtension(name: string) | any | +| activeTexture(texture: GLenum) | void | +| attachShader(program: WebGLProgram, shader: WebGLShader) | void | +| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | +| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | +| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | +| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | +| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| blendEquation(mode: GLenum) | void | +| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | +| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | +| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | +| checkFramebufferStatus(target: GLenum) | GLenum | +| clear(mask: GLbitfield) | void | +| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| clearDepth(depth: GLclampf) | void | +| clearStencil(s: GLint) | void | +| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | +| compileShader(shader: WebGLShader) | void | +| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | +| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| createBuffer() | WebGLBuffer \| null | +| createFramebuffer() | WebGLFramebuffer \| null | +| createProgram() | WebGLProgram \| null | +| createRenderbuffer() | WebGLRenderbuffer \| null | +| createShader(type: GLenum) | WebGLShader \| null | +| createTexture() | WebGLTexture \| null | +| cullFace(mode: GLenum) | void | +| deleteBuffer(buffer: WebGLBuffer \| null) | void | +| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | +| deleteProgram(program: WebGLProgram \| null) | void | +| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | +| deleteShader(shader: WebGLShader \| null) | void | +| deleteTexture(texture: WebGLTexture \| null) | void | +| depthFunc(func: GLenum) | void | +| depthMask(flag: GLboolean) | void | +| depthRange(zNear: GLclampf, zFar: GLclampf) | void | +| detachShader(program: WebGLProgram, shader: WebGLShader) | void | +| disable(cap: GLenum) | void | +| disableVertexAttribArray(index: GLuint) | void | +| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | +| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| enable(cap: GLenum) | void | +| enableVertexAttribArray(index: GLuint) | void | | finish() | void | | flush() | void | -| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | -| frontFace(mode: GLenum) | void | -| generateMipmap(target: GLenum) | void | -| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | -| getAttribLocation(program: WebGLProgram, name: string) | GLint | -| getBufferParameter(target: GLenum, pname: GLenum) | any | -| getParameter(pname: GLenum) | any | +| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | +| frontFace(mode: GLenum) | void | +| generateMipmap(target: GLenum) | void | +| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | +| getAttribLocation(program: WebGLProgram, name: string) | GLint | +| getBufferParameter(target: GLenum, pname: GLenum) | any | +| getParameter(pname: GLenum) | any | | getError() | GLenum | -| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | -| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | -| getProgramInfoLog(program: WebGLProgram) | string \| null | -| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | -| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | -| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | -| getShaderInfoLog(shader: WebGLShader) | string \| null | -| getShaderSource(shader: WebGLShader) | string \| null | -| getTexParameter(target: GLenum, pname: GLenum) | any | -| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | -| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | -| getVertexAttrib(index: GLuint, pname: GLenum) | any | -| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | -| hint(target: GLenum, mode: GLenum) | void | -| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | -| isEnabled(cap: GLenum) | GLboolean | -| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | -| isProgram(program: WebGLProgram \| null) | GLboolean | -| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | -| isShader(shader: WebGLShader \| null) | GLboolean | -| isTexture(texture: WebGLTexture \| null) | GLboolean | -| lineWidth(width: GLfloat) | void | -| linkProgram(program: WebGLProgram) | void | -| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | -| polygonOffset(factor: GLfloat, units: GLfloat) | void | -| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| sampleCoverage(value: GLclampf, invert: GLboolean) | void | -| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| shaderSource(shader: WebGLShader, source: string) | void | -| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilMask(mask: GLuint) | void | -| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | -| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | -| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | -| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | -| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | -| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | -| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | -| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | -| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| useProgram(program: WebGLProgram \| null) | void | -| validateProgram(program: WebGLProgram) | void | -| vertexAttrib1f(index: GLuint, x: GLfloat) | void | -| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | -| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| vertexAttrib1fv(index: GLuint, values: Float32List) | void | -| vertexAttrib2fv(index: GLuint, values: Float32List) | void | -| vertexAttrib3fv(index: GLuint, values: Float32List) | void | -| vertexAttrib4fv(index: GLuint, values: Float32List) | void | -| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | -| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | +| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | +| getProgramInfoLog(program: WebGLProgram) | string \| null | +| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | +| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | +| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | +| getShaderInfoLog(shader: WebGLShader) | string \| null | +| getShaderSource(shader: WebGLShader) | string \| null | +| getTexParameter(target: GLenum, pname: GLenum) | any | +| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | +| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | +| getVertexAttrib(index: GLuint, pname: GLenum) | any | +| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | +| hint(target: GLenum, mode: GLenum) | void | +| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | +| isEnabled(cap: GLenum) | GLboolean | +| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | +| isProgram(program: WebGLProgram \| null) | GLboolean | +| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | +| isShader(shader: WebGLShader \| null) | GLboolean | +| isTexture(texture: WebGLTexture \| null) | GLboolean | +| lineWidth(width: GLfloat) | void | +| linkProgram(program: WebGLProgram) | void | +| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | +| polygonOffset(factor: GLfloat, units: GLfloat) | void | +| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| sampleCoverage(value: GLclampf, invert: GLboolean) | void | +| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| shaderSource(shader: WebGLShader, source: string) | void | +| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilMask(mask: GLuint) | void | +| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | +| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | +| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | +| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | +| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | +| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | +| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | +| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | +| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| useProgram(program: WebGLProgram \| null) | void | +| validateProgram(program: WebGLProgram) | void | +| vertexAttrib1f(index: GLuint, x: GLfloat) | void | +| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | +| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| vertexAttrib1fv(index: GLuint, values: Float32List) | void | +| vertexAttrib2fv(index: GLuint, values: Float32List) | void | +| vertexAttrib3fv(index: GLuint, values: Float32List) | void | +| vertexAttrib4fv(index: GLuint, values: Float32List) | void | +| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | +| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | ## WebGLRenderingContextOverloads @@ -561,24 +561,24 @@ WebGLRenderingContextOverloads | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void; | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index 12cc9789b84cd85960154cd1de1994c8a9f12331..386d1c53dad0df97a9fd0fbbeac33aec45492d5c 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -341,101 +341,101 @@ WebGL2RenderingContextBase | Method| Return Value Type| | -------- | -------- | -| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | -| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | -| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | -| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | -| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | -| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| readBuffer(src: GLenum) | void | -| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | -| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | -| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| getFragDataLocation(program: WebGLProgram, name: string) | GLint | -| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | -| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | -| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | -| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | -| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| vertexAttribI4iv(index: GLuint, values: Int32List) | void | -| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | -| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | -| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | -| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | -| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | -| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | -| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| drawBuffers(buffers: GLenum[]) | void | -| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | -| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | -| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | -| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | -| createQuery() | WebGLQuery \| null | -| deleteQuery(query: WebGLQuery \| null) | void | -| isQuery(query: WebGLQuery \| null) | GLboolean | -| beginQuery(target: GLenum, query: WebGLQuery) | void | -| endQuery(target: GLenum) | void | -| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | -| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | -| createSampler() | WebGLSampler \| null | -| deleteSampler(sampler: WebGLSampler \| null) | void | -| isSampler(sampler: WebGLSampler \| null) | GLboolean | -| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | -| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | -| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | -| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | -| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | -| isSync(sync: WebGLSync \| null) | GLboolean | -| deleteSync(sync: WebGLSync \| null) | void | -| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | -| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | -| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | -| createTransformFeedback() | WebGLTransformFeedback \| null | -| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | -| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | -| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | -| beginTransformFeedback(primitiveMode: GLenum) | void | +| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | +| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | +| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | +| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | +| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | +| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| readBuffer(src: GLenum) | void | +| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | +| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | +| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| getFragDataLocation(program: WebGLProgram, name: string) | GLint | +| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | +| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | +| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | +| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | +| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| vertexAttribI4iv(index: GLuint, values: Int32List) | void | +| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | +| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | +| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | +| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | +| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | +| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | +| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| drawBuffers(buffers: GLenum[]) | void | +| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | +| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | +| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | +| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | +| createQuery() | WebGLQuery \| null | +| deleteQuery(query: WebGLQuery \| null) | void | +| isQuery(query: WebGLQuery \| null) | GLboolean | +| beginQuery(target: GLenum, query: WebGLQuery) | void | +| endQuery(target: GLenum) | void | +| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | +| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | +| createSampler() | WebGLSampler \| null | +| deleteSampler(sampler: WebGLSampler \| null) | void | +| isSampler(sampler: WebGLSampler \| null) | GLboolean | +| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | +| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | +| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | +| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | +| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | +| isSync(sync: WebGLSync \| null) | GLboolean | +| deleteSync(sync: WebGLSync \| null) | void | +| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | +| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | +| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | +| createTransformFeedback() | WebGLTransformFeedback \| null | +| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | +| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | +| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | +| beginTransformFeedback(primitiveMode: GLenum) | void | | endTransformFeedback() | void | -| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | -| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | +| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | | pauseTransformFeedback() | void | | resumeTransformFeedback() | void | -| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | -| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | -| getIndexedParameter(target: GLenum, index: GLuint) | any | -| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | -| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | -| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | -| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | -| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | -| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | -| createVertexArray() | WebGLVertexArrayObject \| null | -| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | -| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | -| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | +| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | +| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | +| getIndexedParameter(target: GLenum, index: GLuint) | any | +| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | +| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | +| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | +| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | +| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | +| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | +| createVertexArray() | WebGLVertexArrayObject \| null | +| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | +| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | +| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | ## WebGL2RenderingContextOverloads @@ -444,36 +444,36 @@ WebGL2RenderingContextOverloads | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | -| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | +| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 885802b44997a358ec30fa363fc292d1efa6971c..b5eab0ff1825741b77cf81ae966c499aff4c1398 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -1,9 +1,14 @@ # Window -The **Window** module provides basic capabilities for managing windows, including creating and destroying windows and setting serial port attributes. +The `Window` module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. -> **NOTE**
-> +This module provides the following common window-related functions: + +- [Window](#window): the current window instance, which is the basic unit managed by the window manager. +- [WindowStage](#windowstage9): window manager that manages windows. + +> **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 @@ -18,23 +23,23 @@ Enumerates the window types. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value | Description | +| Name | Value| Description | | ----------------- | ------ | ------------------ | -| TYPE_APP | 0 | Application subwindow. | +| TYPE_APP | 0 | Application subwindow. This type can be used only in the FA model.| | TYPE_SYSTEM_ALERT | 1 | System alert window.| -| TYPE_INPUT_METHOD9+ | 2 | Input method window.| -| TYPE_STATUS_BAR9+ | 3 | Status bar.| -| TYPE_PANEL9+ | 4 | Notification panel.| -| TYPE_KEYGUARD9+ | 5 | Lock screen.| -| TYPE_VOLUME_OVERLAY9+ | 6 | Volume bar.| -| TYPE_NAVIGATION_BAR9+ | 7 | Navigation bar.| -| TYPE_FLOAT9+ | 8 | Floating window.| -| TYPE_WALLPAPER9+ | 9 | Wallpaper.| -| TYPE_DESKTOP9+ | 10 | Home screen.| -| TYPE_LAUNCHER_RECENT9+ | 11 | Recent tasks screen.| -| TYPE_LAUNCHER_DOCK9+ | 12 | Dock bar on the home screen.| -| TYPE_VOICE_INTERACTION9+ | 13 | Voice assistant.| -| TYPE_POINTER9+ | 14 | Mouse.| +| TYPE_INPUT_METHOD9+ | 2 | Input method window. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_STATUS_BAR9+ | 3 | Status bar. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_PANEL9+ | 4 | Notification panel. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_KEYGUARD9+ | 5 | Lock screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_VOLUME_OVERLAY9+ | 6 | Volume bar. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_NAVIGATION_BAR9+ | 7 | Navigation bar. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_FLOAT9+ | 8 | Floating window. This type can be used only in the stage model.
**Required permissions**: ohos.permission.SYSTEM_FLOAT_WINDOW| +| TYPE_WALLPAPER9+ | 9 | Wallpaper. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_DESKTOP9+ | 10 | Home screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_LAUNCHER_RECENT9+ | 11 | Recent tasks screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_LAUNCHER_DOCK9+ | 12 | Dock bar on the home screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_VOICE_INTERACTION9+ | 13 | Voice assistant. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_POINTER9+ | 14 | Mouse. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| ## AvoidAreaType7+ @@ -42,26 +47,41 @@ Enumerates the types of the area where the window cannot be displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value | Description | -| ----------- | ------ | ------------------ | -| TYPE_SYSTEM | 0 | Default area of the system.| -| TYPE_CUTOUT | 1 | Notch. | +| Name | Value | Description | +|----------------------------------|-----| ----------------- | +| TYPE_SYSTEM | 0 | Default area of the system.| +| TYPE_CUTOUT | 1 | Notch. | +| TYPE_SYSTEM_GESTURE9+ | 2 | Gesture area. | +| TYPE_KEYBOARD9+ | 3 | Soft keyboard area. | ## WindowMode7+ -Enumerates the window modes of an application. +Enumerates the window modes. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Value | Description | +| ---------- | ---- | ----------------------------- | +| UNDEFINED | 1 | The window mode is not defined by the application. | +| FULLSCREEN | 2 | The application is displayed in full screen. | +| PRIMARY | 3 | The application is displayed in the primary window in split-screen mode. | +| SECONDARY | 4 | The application is displayed in the secondary window in split-screen mode. | +| FLOATING | 5 | The application is displayed in a floating window.| + +## WindowLayoutMode9+ + +Enumerates the window layout modes. This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value | Description | -| ---------- | ------ | ----------------------------- | -| UNDEFINED | 1 | The window mode is not defined by the application. | -| FULLSCREEN | 2 | The application is displayed in full screen. | -| PRIMARY | 3 | The application is displayed in the primary window in split-screen mode. | -| SECONDARY | 4 | The application is displayed in the secondary window in split-screen mode. | -| FLOATING | 5 | The application is displayed in a floating window.| +| Name | Value | Description | +| ---------- | ---- | ----------------------------- | +| WINDOW_LAYOUT_MODE_CASCADE | 0 | Cascade mode. | +| WINDOW_LAYOUT_MODE_TILE | 1 | Tile mode. | ## SystemBarProperties @@ -71,13 +91,34 @@ Describes the properties of the status bar and navigation bar. | Name | Type| Readable| Writable| Description | | -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| statusBarColor | string | Yes | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **\#00FF00** or **\#FF00FF00**.| +| statusBarColor | string | Yes | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | isStatusBarLightIcon7+ | boolean | No | Yes | Whether any icon on the status bar is highlighted. | | statusBarContentColor8+ | string | No | Yes | Color of the text on the status bar. | -| navigationBarColor | string | Yes | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **\#00FF00** or **\#FF00FF00**.| +| navigationBarColor | string | Yes | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | isNavigationBarLightIcon7+ | boolean | No | No | Whether any icon on the navigation bar is highlighted. | | navigationBarContentColor8+ | string | No | Yes | Color of the text on the navigation bar. | +## Orientation9+ + +Enumerates the window orientations. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Value | Description | +| ------------------------------------- | ---- | ----------------------------- | +| UNSPECIFIED | 0 | Unspecified. The orientation is determined by the system.| +| PORTRAIT | 1 | Portrait. | +| LANDSCAPE | 2 | Landscape. | +| PORTRAIT_INVERTED | 3 | Reverse portrait. | +| LANDSCAPE_INVERTED | 4 | Reverse landscape.| +| AUTO_ROTATION | 5 | Auto rotation.| +| AUTO_ROTATION_PORTRAIT | 6 | Auto rotation in the vertical direction.| +| AUTO_ROTATION_LANDSCAPE | 7 | Auto rotation in the horizontal direction.| +| AUTO_ROTATION_RESTRICTED | 8 | Switched-determined auto rotation.| +| AUTO_ROTATION_PORTRAIT_RESTRICTED | 9 | Switched-determined auto rotation in the vertical direction.| +| AUTO_ROTATION_LANDSCAPE_RESTRICTED | 10 | Switched-determined auto rotation in the horizontal direction.| +| LOCKED | 11 | Locked.| + ## SystemBarRegionTint8+ Describes the callback for a single system bar. @@ -91,7 +132,7 @@ This is a system API and cannot be called by third-party applications. | type | [WindowType](#windowtype) | Yes | Yes | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| | isEnable | boolean | Yes | Yes | Whether the system bar is displayed. | | region | [Rect](#rect) | Yes | Yes | Current position and size of the system bar. | -| backgroundColor | string | Yes | Yes | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **\#00FF00** or **\#FF00FF00**.| +| backgroundColor | string | Yes | Yes | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | contentColor | string | Yes | Yes | Color of the text on the system bar. | ## SystemBarTintState8+ @@ -102,10 +143,10 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| ---------- | --------------------------------------------------- | ---- | ---- | -------------------------- | -| displayId | number | Yes | No | ID of the current physical screen. | -| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | Yes | All system bar information changed.| +| Name | Type | Readable| Writable| Description | +| ---------- | --------------------------------------------------- | ---- | ---- | ---------------------------- | +| displayId | number | Yes | No | ID of the current physical screen. | +| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | Yes | All system bar information that has been changed.| ## Rect7+ @@ -128,6 +169,7 @@ Describes the area where the window cannot be displayed. | Name | Type | Readable| Writable| Description | | ---------- | ------------- | ---- | ---- | ------------------ | +| visible9+ | boolean | Yes | Yes | Whether the area is visible.| | leftRect | [Rect](#rect) | Yes | Yes | Rectangle on the left of the screen.| | topRect | [Rect](#rect) | Yes | Yes | Rectangle at the top of the screen.| | rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.| @@ -154,16 +196,16 @@ Describes the window properties. | ------------------------------- | ------------------------- | ---- | ---- | -------------------------------------------- | | windowRect7+ | [Rect](#rect) | Yes | Yes | Window size. | | type7+ | [WindowType](#windowtype) | Yes | Yes | Window type. | -| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is **false**. | -| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is **false**. | -| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is **true**. | -| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is **true**. | -| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value **1** indicates the maximum brightness. | -| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value **1** indicates the maximum dimness.
This attribute is supported since API version 7 and deprecated since API version 9.
| -| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is **false**. | -| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is **false**. | -| isRoundCorner7+ | boolean | Yes | Yes | Whether the window has rounded corners. The default value is **false**. | -| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is **false**. | +| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | +| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | +| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | +| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | +| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | +| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.
**NOTE**
This attribute is deprecated since API version 9.
| +| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | +| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | +| isRoundCorner7+ | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. | +| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | ## ColorSpace8+ @@ -182,32 +224,30 @@ create(id: string, type: WindowType, callback: AsyncCallback<Window>): voi Creates a subwindow. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 8. You are advised to use [window.create8+](#windowcreate8) instead. +This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | -------------------------- | -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------ | +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype) | Yes | Window type. | | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created.| **Example** - ```js - var windowClass = null; - window.create("first", window.WindowType.TYPE_APP, (err, data) => { - if (err.code) { - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('SubWindow created. Data: ' + JSON.stringify(data)) - windowClass.resetSize(500, 1000); - }); - ``` +```js +var windowClass = null; + let promise = window.create("first", window.WindowType.TYPE_APP); + promise.then((data)=> { + windowClass = data; + console.info('SubWindow created. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); + }); +``` ## window.create7+ @@ -215,7 +255,7 @@ create(id: string, type: WindowType): Promise<Window> Creates a subwindow. This API uses a promise to return the result. -This API is deprecated since API version 8. You are advised to use [window.create8+](#windowcreate8) instead. +This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -228,22 +268,22 @@ This API is deprecated since API version 8. You are advised to use [window.creat **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------- | +| Type | Description | +| -------------------------------- | --------------------------------------- | | Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** - ```js - var windowClass = null; - let promise = window.create("first", window.WindowType.TYPE_APP); - promise.then((data)=> { - windowClass = data; - console.info('SubWindow created. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var windowClass = null; +let promise = window.create("first", window.WindowType.TYPE_APP); +promise.then((data)=> { + windowClass = data; + console.info('SubWindow created. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); +}); +``` ## window.create8+ @@ -257,25 +297,25 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| +| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype) | Yes | Window type. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window created. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window created. | **Example** - ```js - var windowClass = null; - window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { - if (err.code) { - console.error('Failed to create the Window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Window created. Data: ' + JSON.stringify(data)) - windowClass.resetSize(500, 1000); - }); - ``` +```js +var windowClass = null; + window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { + if (err.code) { + console.error('Failed to create the Window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Window created. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); +}); +``` ## window.create8+ @@ -289,28 +329,28 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| +| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype) | Yes | Window type. | **Return value** -| Type | Description | -| -------------------------------- | ----------------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the window created.| +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the window created. | **Example** - ```js - var windowClass = null; - let promise = window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT); - promise.then((data)=> { - windowClass = data; - console.info('Window created. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to create the Window. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var windowClass = null; +let promise = window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT); +promise.then((data)=> { + windowClass = data; + console.info('Window created. Data:' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); +}); +``` ## window.find7+ @@ -322,24 +362,24 @@ Finds a window based on the ID. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ---------------------------- | -| id | string | Yes | Window ID. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------ | +| id | string | Yes | Window ID. | | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window found.| **Example** - ```js - var windowClass = null; - window.find("alertWindow", (err, data) => { - if (err.code) { - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)) - }); - ``` +```js +var windowClass = null; + window.find("alertWindow", (err, data) => { + if (err.code) { + console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('window found. Data: ' + JSON.stringify(data)); +}); +``` ## window.find7+ @@ -357,22 +397,22 @@ Finds a window based on the ID. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------------------------- | ----------------------------------------------- | +| Type | Description | +| -------------------------------- | ------------------------------------- | | Promise<[Window](#window)> | Promise used to return the window found.| **Example** - ```js - var windowClass = null; - let promise = window.find("alertWindow"); - promise.then((data)=> { - windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var windowClass = null; +let promise = window.find("alertWindow"); +promise.then((data)=> { + windowClass = data; + console.info('window found. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); +}); +``` ## window.getTopWindow @@ -380,29 +420,29 @@ getTopWindow(callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 8. You are advised to use [window.getTopWindow8+](#windowgettopwindow8) instead. +This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | -------------------------------------- | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | -------------------------------------------- | | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained.| **Example** - ```js - var windowClass = null; - window.getTopWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); - }); - ``` +```js +var windowClass = null; +window.getTopWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}); +``` ## window.getTopWindow @@ -410,28 +450,28 @@ getTopWindow(): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. -This API is deprecated since API version 8. You are advised to use [window.getTopWindow8+](#windowgettopwindow8) instead. +This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| -------------------------------- | --------------------------------------------------------- | +| Type | Description | +| -------------------------------- | ----------------------------------------------- | | Promise<[Window](#window)> | Promise used to return the top window obtained.| **Example** - ```js - var windowClass = null; - let promise = window.getTopWindow(); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - }) - ``` +```js +var windowClass = null; +let promise = window.getTopWindow(); +promise.then((data)=> { + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); +}) +``` ## window.getTopWindow8+ @@ -445,22 +485,22 @@ Obtains the top window of the current application. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [AbilityContext](js-apis-ability-context.md). | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | +| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | **Example** - ```js - var windowClass = null; - window.getTopWindow(this.context, (err, data) => { - if (err.code) { - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); - }); - ``` +```js +var windowClass = null; +window.getTopWindow(this.context, (err, data) => { + if (err.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}); +``` ## window.getTopWindow8+ @@ -474,26 +514,215 @@ Obtains the top window of the current application. This API uses a promise to re | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [AbilityContext](js-apis-ability-context.md). | +| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| **Return value** -| Type | Description | -| -------------------------------- | --------------------------------------------------------- | +| Type | Description | +| -------------------------------- | ----------------------------------------------- | | Promise<[Window](#window)> | Promise used to return the top window obtained.| **Example** - ```js - var windowClass = null; - let promise = window.getTopWindow(this.context); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - }) - ``` +```js +var windowClass = null; +let promise = window.getTopWindow(this.context); +promise.then((data)=> { + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); +}) +``` + +## window.minimizeAll9+ +minimizeAll(id: number, callback: AsyncCallback<void>): void + +Minimizes all windows on a display. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------- | +| id | number | Yes | ID of the [display](js-apis-display.md#display). | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +import display from '@ohos.display' +import window from '@ohos.window' + +var displayClass = null; +display.getDefaultDisplay((err, data) => { + if(err.code) { + return; + } + displayClass = data; + window.minimizeAll(displayClass.id, (err, data) => { + if(err.code) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in minimizing all windows.'); + }); +}); +``` + +## window.minimizeAll9+ +minimizeAll(id: number): Promise<void> + +Minimizes all windows on a display. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------- | +| id | number | Yes | ID of the [display](js-apis-display.md#display).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import display from '@ohos.display' +import window from '@ohos.window' + +var displayClass = null; +display.getDefaultDisplay((err, data) => { + if(err.code) { + return; + } + displayClass = data; + let promise = window.minimizeAll(displayClass.id); + promise.then((data)=> { + console.info('Succeeded in minimizing all windows.'); + }).catch((err)=>{ + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); + }) +}); +``` + +## window.toggleShownStateForAllAppWindows9+ +toggleShownStateForAllAppWindows(callback: AsyncCallback<void>): void + +Hides or restores the application's windows during quick multi-window switching. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +window.toggleShownStateForAllAppWindows((err, data) => { + if (err.code) { + console.error('Failed to toggle shown state for all app windows. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in toggling shown state for all app windows.'); +}) +``` + +## window.toggleShownStateForAllAppWindows9+ +toggleShownStateForAllAppWindows(): Promise<void> + +Hides or restores the application's windows during quick multi-window switching. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = window.toggleShownStateForAllAppWindows(); +promise.then((data)=> { + console.info('Succeeded in toggling shown state for all app windows. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to toggle shown state for all app windows. Cause: ' + JSON.stringify(err)); +}) +``` + +## window.setWindowLayoutMode9+ +setWindowLayoutMode(mode: WindowLayoutMode, callback: AsyncCallback<void>): void + +Sets the window layout mode. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------- | +| mode | [WindowLayoutMode](#windowlayoutmode9) | Yes | Window layout mode to set.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE, (data) => { + console.info('Succeeded in setting window layout mode. Data: ' + JSON.stringify(data)); +}); +``` + +## window.setWindowLayoutMode9+ +setWindowLayoutMode(mode: WindowLayoutMode): Promise<void> + +Sets the window layout mode. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------- | +| mode | [WindowLayoutMode](#windowlayoutmode9) | Yes | Window layout mode to set.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE); +promise.then((data)=> { + console.info('Succeeded in setting window layout mode. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(err)); +}) +``` ## on('systemBarTintChange')8+ @@ -509,17 +738,16 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **systemBarTintChange**, indicating the property change event of the status bar and navigation bar.| -| callback | Callback<[SystemBarTintState](#systembartintstate)> | Yes | Callback used to return the information. | +| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| callback | Callback<[SystemBarTintState](#systembartintstate)> | Yes | Callback used to return the properties of the status bar and navigation bar. | **Example** - ```js - var type = 'systemBarTintChange'; - windowClass.on(type, (data) => { - console.info('Succeeded in enabling the listener for systemBarTint changes. Data: ' + JSON.stringify(data)); - }); - ``` +```js +window.on('systemBarTintChange', (data) => { + console.info('Succeeded in enabling the listener for systemBarTint changes. Data: ' + JSON.stringify(data)); +}); +``` ## off('systemBarTintChange')8+ @@ -535,19 +763,20 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **systemBarTintChange**, indicating the property change event of the status bar and navigation bar.| -| callback | Callback<[SystemBarTintState](#systembartintstate)> | No | Callback used to return the information. | +| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| callback | Callback<[SystemBarTintState](#systembartintstate)> | No | Callback used to return the properties of the status bar and navigation bar. | **Example** - ```js - var type = 'systemBarTintChange'; - windowClass.off(type); - ``` +```js +window.off('systemBarTintChange'); +``` ## Window -In the following API examples, you must use [getTopWindow()](#windowgettopwindow), [create()](#windowcreate7), or [find()](#windowfind7) to obtain a **Window** instance and then call a method in this instance. +Represents the current window instance, which is the basic unit managed by the window manager. + +In the following API examples, you must use [getTopWindow()](#windowgettopwindow), [create()](#windowcreate7), or [find()](#windowfind7) to obtain a `Window` instance and then call a method in this instance. ### hide7+ @@ -563,19 +792,19 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js - windowClass.hide((err, data) => { - if (err.code) { - console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); - return; - } - console.info('window hidden. data: ' + JSON.stringify(data)) - }) - ``` +```js +windowClass.hide((err, data) => { + if (err.code) { + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('window hidden. data: ' + JSON.stringify(data)); +}) +``` ### hide7+ @@ -589,20 +818,20 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.hide(); - promise.then((data)=> { - console.info('window hidden. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); - }) - ``` +```js +let promise = windowClass.hide(); +promise.then((data)=> { + console.info('window hidden. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); +}) +``` ### show7+ @@ -616,19 +845,19 @@ Shows this window. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js - windowClass.show((err, data) => { - if (err.code) { - console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)) - }) - ``` +```js +windowClass.show((err, data) => { + if (err.code) { + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); +}) +``` ### show7+ @@ -640,20 +869,20 @@ Shows this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.show(); - promise.then((data)=> { - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); - }) - ``` +```js +let promise = windowClass.show(); +promise.then((data)=> { + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); +}) +``` ### destroy7+ @@ -667,19 +896,19 @@ Destroys this window. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js - windowClass.destroy((err, data) => { - if (err.code) { - console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)) - }) - ``` +```js +windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); +}) +``` ### destroy7+ @@ -691,20 +920,20 @@ Destroys this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.destroy(); - promise.then((data)=> { - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); - }) - ``` +```js +let promise = windowClass.destroy(); +promise.then((data)=> { + console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); +}) +``` ### moveTo7+ @@ -720,20 +949,20 @@ Moves this window. This API uses an asynchronous callback to return the result. | -------- | ------------------------- | ---- | ------------------------------------------------- | | x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| | y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - windowClass.moveTo(300, 300, (err, data)=>{ - if (err.code) { - console.error('Failed to move the window. Cause:' + JSON.stringify(err)); - return; - } - console.info('Window moved. Data: ' + JSON.stringify(data)) - - }); - ``` +```js +windowClass.moveTo(300, 300, (err, data)=>{ + if (err.code) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window moved. Data: ' + JSON.stringify(data)); + +}); +``` ### moveTo7+ @@ -752,20 +981,20 @@ Moves this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.moveTo(300, 300); - promise.then((data)=> { - console.info('Window moved. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); - }) - ``` +```js +let promise = windowClass.moveTo(300, 300); +promise.then((data)=> { + console.info('Window moved. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); +}) +``` ### resetSize7+ @@ -781,19 +1010,19 @@ Changes the size of this window. This API uses an asynchronous callback to retur | -------- | ------------------------- | ---- | -------------------------- | | width | number | Yes | New width of the window, in px.| | height | number | Yes | New height of the window, in px.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - windowClass.resetSize(500, 1000, (err, data) => { - if (err.code) { - console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); - return; - } - console.info('Window size changed. Data: ' + JSON.stringify(data)) - }); - ``` +```js +windowClass.resetSize(500, 1000, (err, data) => { + if (err.code) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window size changed. Data: ' + JSON.stringify(data)); +}); +``` ### resetSize7+ @@ -812,20 +1041,20 @@ Changes the size of this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.resetSize(500, 1000); - promise.then((data)=> { - console.info('Window size changed. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.resetSize(500, 1000); +promise.then((data)=> { + console.info('Window size changed. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); +}); +``` ### setWindowType7+ @@ -842,20 +1071,20 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | | type | [WindowType](#windowtype) | Yes | Window type.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js - var type = window.TYPE_APP; - windowClass.setWindowType(type, (err, data) => { - if (err.code) { - console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)) - }); - ``` +```js +var type = window.WindowType.TYPE_APP; +windowClass.setWindowType(type, (err, data) => { + if (err.code) { + console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)); +}); +``` ### setWindowType7+ @@ -875,21 +1104,21 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var type = window.TYPE_APP; - let promise = windowClass.setWindowType(type); - promise.then((data)=> { - console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var type = window.WindowType.TYPE_APP; +let promise = windowClass.setWindowType(type); +promise.then((data)=> { + console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); +}); +``` ### getProperties @@ -901,21 +1130,21 @@ Obtains the properties of this window. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------------- | ---- | ------------------ | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | ---------------------------- | | callback | AsyncCallback<[WindowProperties](#windowproperties)> | Yes | Callback used to return the window properties.| **Example** - ```js - windowClass.getProperties((err, data) => { - if (err.code) { - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); - }); - ``` +```js +windowClass.getProperties((err, data) => { + if (err.code) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +}); +``` ### getProperties @@ -927,24 +1156,24 @@ Obtains the properties of this window. This API uses a promise to return the res **Return value** -| Type | Description | -| ---------------------------------------------------- | ------------------------------------- | +| Type | Description | +| ---------------------------------------------------- | ------------------------------- | | Promise<[WindowProperties](#windowproperties)> | Promise used to return the window properties.| **Example** - ```js - let promise = windowClass.getProperties(); - promise.then((data)=> { - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.getProperties(); +promise.then((data)=> { + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); +}); +``` ### getAvoidArea7+ -getAvoidArea(type: AvoidAreaType, callback: AsyncCallback<AvoidArea>): void +getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void Obtains the area where this window cannot be displayed, for example, the system bar area and notch. This API uses an asynchronous callback to return the result. @@ -952,27 +1181,27 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch.| -| callback | AsyncCallback<[AvoidArea](#avoidarea)> | Yes | Callback used to return the area. | +| Name | Type | Mandatory| Description | +| -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.| +| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** - ```js - var type = window.AvoidAreaType.TYPE_SYSTEM; - windowClass.getAvoidArea(type, (err, data) => { - if (err.code) { - console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); - }); - ``` +```js +var type = window.AvoidAreaType.TYPE_SYSTEM; +windowClass.getAvoidArea(type, (err, data) => { + if (err.code) { + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +}); +``` ### getAvoidArea7+ -getAvoidArea(type: AvoidAreaType): Promise<AvoidArea> +getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise<[AvoidArea](#avoidarea7)> Obtains the area where this window cannot be displayed, for example, the system bar area and notch. This API uses a promise to return the result. @@ -980,26 +1209,26 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------- | ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch.| +| Name| Type | Mandatory| Description | +| ------ |----------------------------------| ---- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.| **Return value** -| Type | Description | -| -------------------------------------- | --------------------------------------------- | -| Promise<[AvoidArea](#avoidarea)> | Promise used to return the area.| +| Type | Description | +|-----------------------------------------| ----------------------------------- | +| Promise<[AvoidArea](#avoidarea7)> | Promise used to return the area.| **Example** - ```js - let promise = windowClass.getAvoidArea(); - promise.then((data)=> { - console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.getAvoidArea(); +promise.then((data)=> { + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); +}); +``` ### setFullScreen @@ -1014,20 +1243,20 @@ Sets whether to enable the full-screen mode for this window. This API uses an as | Name | Type | Mandatory| Description | | ------------ | ------------------------- | ---- | ---------------------------------------------- | | isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var isFullScreen = true; - windowClass.setFullScreen(isFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)) - }); - ``` +```js +var isFullScreen = true; +windowClass.setFullScreen(isFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); +}); +``` ### setFullScreen @@ -1045,21 +1274,21 @@ Sets whether to enable the full-screen mode for this window. This API uses a pro **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var isFullScreen = true; - let promise = windowClass.setFullScreen(isFullScreen); - promise.then((data)=> { - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var isFullScreen = true; +let promise = windowClass.setFullScreen(isFullScreen); +promise.then((data)=> { + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); +}); +``` ### setLayoutFullScreen7+ @@ -1074,20 +1303,20 @@ Sets whether to enable the full-screen mode for the window layout. This API uses | Name | Type | Mandatory| Description | | ------------------ | ------------------------- | ---- | ------------------------------------------------------------ | | isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var isLayoutFullScreen= true; - windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)) - }); - ``` +```js +var isLayoutFullScreen= true; +windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); +}); +``` ### setLayoutFullScreen7+ @@ -1105,21 +1334,21 @@ Sets whether to enable the full-screen mode for the window layout. This API uses **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var isLayoutFullScreen = true; - let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen); - promise.then((data)=> { - console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); - }); - ``` +```js +var isLayoutFullScreen = true; +let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen); +promise.then((data)=> { + console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); +}); +``` ### setSystemBarEnable7+ @@ -1133,21 +1362,21 @@ Sets whether to display the status bar and navigation bar in this window. This A | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| names | Array | Yes | Whether to display the status bar and navigation bar. For example, to display the status bar and navigation bar, set this parameter to **["status", "navigation"]**. By default, they are not displayed.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to `["status", "navigation"]`. By default, they are not displayed.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var names = ["status", "navigation"]; - windowClass.setSystemBarEnable(names, (err, data) => { - if (err.code) { - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)) - }); - ``` +```js +var names = ["status", "navigation"]; +windowClass.setSystemBarEnable(names, (err, data) => { + if (err.code) { + console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); +}); +``` ### setSystemBarEnable7+ @@ -1161,25 +1390,25 @@ Sets whether to display the status bar and navigation bar in this window. This A | Name| Type | Mandatory| Description | | ------ | ----- | ---- | ------------------------------------------------------------ | -| names | Array | Yes | Whether to display the status bar and navigation bar. For example, to display the status bar and navigation bar, set this parameter to **["status", "navigation"]**. By default, they are not displayed.| +| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to `["status", "navigation"]`. By default, they are not displayed.| **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var names = ["status", "navigation"]; - let promise = windowClass.setSystemBarEnable(names); - promise.then((data)=> { - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); - }); - ``` +```js +var names = ["status", "navigation"]; +let promise = windowClass.setSystemBarEnable(names); +promise.then((data)=> { + console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); +}); +``` ### setSystemBarProperties @@ -1191,32 +1420,32 @@ Sets the properties of the status bar and navigation bar in this window. This AP **Parameters** -| Name | Type | Mandatory| Description | -| ------------------- | ------------------------------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------- | ---- | ---------------------- | | SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | - -**Example** - - ```js - var SystemBarProperties={ - statusBarColor: '#ff00ff', - navigationBarColor: '#00ff00', - // The following properties are supported since API version 7. - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, - // The following properties are supported since API version 8. - statusBarContentColor:'#ffffff', - navigationBarContentColor:'#00ffff' - }; - windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { - if (err.code) { - console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)) - }); - ``` +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +var SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 7. + isStatusBarLightIcon: true, + isNavigationBarLightIcon:false, + // The following properties are supported since API version 8. + statusBarContentColor:'#ffffff', + navigationBarContentColor:'#00ffff' +}; +windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { + if (err.code) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); +}); +``` ### setSystemBarProperties @@ -1228,69 +1457,129 @@ Sets the properties of the status bar and navigation bar in this window. This AP **Parameters** -| Name | Type | Mandatory| Description | -| ------------------- | ------------------------------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------- | ---- | ---------------------- | | SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar.| **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| - -**Example** - - ```js - var SystemBarProperties={ - statusBarColor: '#ff00ff', - navigationBarColor: '#00ff00', - // The following properties are supported since API version 7. - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, - // The following properties are supported since API version 8. - statusBarContentColor:'#ffffff', - navigationBarContentColor:'#00ffff' - }; - let promise = windowClass.setSystemBarProperties(SystemBarProperties); - promise.then((data)=> { - console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); - }); - ``` +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| -### loadContent7+ +**Example** -loadContent(path: string, callback: AsyncCallback<void>): void +```js +var SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 7. + isStatusBarLightIcon: true, + isNavigationBarLightIcon:false, + // The following properties are supported since API version 8. + statusBarContentColor:'#ffffff', + navigationBarContentColor:'#00ffff' +}; +let promise = windowClass.setSystemBarProperties(SystemBarProperties); +promise.then((data)=> { + console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); +}); +``` -Loads content to this window. This API uses an asynchronous callback to return the result. +### setPreferredOrientation9+ + +setPreferredOrientation(orientation: Orientation, callback: AsyncCallback<void>): void + +Sets the preferred orientation for this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------- | ---- | ---------------------- | +| Orientation | [Orientation](#orientation9) | Yes | Orientation to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +var orientation = window.Orientation.AUTO_ROTATION; +windowClass.setPreferredOrientation(orientation, (err, data) => { + if (err.code) { + console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window orientation. Data: ' + JSON.stringify(data)); +}); +``` + +### setPreferredOrientation9+ + +setPreferredOrientation(orientation: Orientation): Promise<void> + +Sets the preferred orientation for this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------- | ---- | ---------------------- | +| Orientation | [Orientation](#orientation9) | Yes | Orientation to set. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +var orientation = window.Orientation.AUTO_ROTATION; +let promise = windowClass.setPreferredOrientation(orientation); +promise.then((data)=> { + console.info('Succeeded in setting the window orientation. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the window orientation. Cause: ' + JSON.stringify(err)); +}); +``` + +### loadContent7+ + +loadContent(path: string, callback: AsyncCallback<void>): void + +Loads content from a page to this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------- | | path | string | Yes | Path of the page from which the content will be loaded.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - windowClass.loadContent("pages/page2/page2", (err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) - }); - ``` +```js +windowClass.loadContent("pages/page2/page2", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); +}); +``` ### loadContent7+ loadContent(path: string): Promise<void> -Loads content to this window. This API uses a promise to return the result. +Loads content from a page to this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1302,21 +1591,101 @@ Loads content to this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.loadContent("pages/page2/page2"); - promise.then((data)=> { - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.loadContent("pages/page2/page2"); +promise.then((data)=> { + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); +}); +``` +### loadContent9+ + +loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void + +Loads content from a page associated with a local storage to this window. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```ts +class myAbility extends Ability { + storage : LocalStorage + onWindowStageCreate(windowStage) { + this.storage = new LocalStorage(); + this.storage.setOrCreate("storageSimpleProp",121); + console.log('onWindowStageCreate'); + windowStage.loadContent("pages/page2",this.storage,(err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + }); + } +} +``` + +### loadContent9+ + +loadContent(path: string, storage: LocalStorage): Promise<void> +Loads content from a page associated with a local storage to this window. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +class myAbility extends Ability { + storage : LocalStorage + onWindowStageCreate(windowStage) { + this.storage = new LocalStorage(); + this.storage.setOrCreate("storageSimpleProp",121); + console.log('onWindowStageCreate'); + var windowClass = null; + let promise = windowStage.loadContent("pages/page2",this.storage); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + }) + } +} +``` ### isShowing7+ isShowing(callback: AsyncCallback<boolean>): void @@ -1327,21 +1696,21 @@ Checks whether this window is displayed. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the window is displayed.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| **Example** - ```js - windowClass.isShowing((err, data) => { - if (err.code) { - console.error('Failed to check whether the window is showing. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)) - }); - ``` +```js +windowClass.isShowing((err, data) => { + if (err.code) { + console.error('Failed to check whether the window is showing. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); +}); +``` ### isShowing7+ @@ -1353,20 +1722,20 @@ Checks whether this window is displayed. This API uses a promise to return the r **Return value** -| Type | Description | -| ---------------------- | ----------------------------------------------------- | -| Promise<boolean> | Promise used to return whether the window is displayed.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| **Example** - ```js - let promise = windowClass.isShowing(); - promise.then((data)=> { - console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.isShowing(); +promise.then((data)=> { + console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(err)); +}); +``` ### on('windowSizeChange')7+ @@ -1378,19 +1747,18 @@ Enables listening for window size changes. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | -------------------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **windowSizeChange**, indicating the window size change event.| -| callback | Callback<[Size](#size)> | Yes | Callback used to return the information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | -------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| callback | Callback<[Size](#size7)> | Yes | Callback used to return the window size. | **Example** - ```js - var type = 'windowSizeChange'; - windowClass.on(type, (data) => { - console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); - }); - ``` +```js +windowClass.on('windowSizeChange', (data) => { + console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); +}); +``` ### off('windowSizeChange')7+ @@ -1404,61 +1772,109 @@ Disables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | -------------------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **windowSizeChange**, indicating the window size change event.| -| callback | Callback<[Size](#size)> | No | Callback used to return the information. | +| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| callback | Callback<[Size](#size)> | No | Callback used to return the window size. | **Example** - ```js - var type = 'windowSizeChange'; - windowClass.off(type); - ``` +```js +windowClass.off('windowSizeChange'); +``` -### on('systemAvoidAreaChange')7+ +### on('systemAvoidAreaChange')(deprecated) -on(type: 'systemAvoidAreaChange', callback: Callback<AvoidArea>): void +on(type: 'systemAvoidAreaChange', callback: Callback<[AvoidArea](#avoidarea7)>): void Enables listening for changes to the area where the window cannot be displayed. +> **NOTE** +> +> This API is deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **systemAvoidAreaChange**, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea)> | Yes | Callback used to return the information. | +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| callback | Callback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** - ```js - var type = 'systemAvoidAreaChange'; - windowClass.on(type, (data) => { - console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data)); - }); - ``` +```js +windowClass.on('systemAvoidAreaChange', (data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data)); +}); +``` -### off('systemAvoidAreaChange')7+ +### off('systemAvoidAreaChange')(deprecated) -off(type: 'systemAvoidAreaChange', callback?: Callback<AvoidArea>): void +off(type: 'systemAvoidAreaChange', callback?: Callback<[AvoidArea](#avoidarea7)>): void Disables listening for changes to the area where the window cannot be displayed. +> **NOTE** +> +> This API is deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **systemAvoidAreaChange**, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea)> | No | Callback used to return the information. | +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | **Example** - ```js - var type = 'systemAvoidAreaChange'; - windowClass.off(type); - ``` +```js +windowClass.off('systemAvoidAreaChange'); +``` + + +### on('avoidAreaChange')9+ + +on(type: 'avoidAreaChange', callback: Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}>): void + +Enables listening for changes to the area where the window cannot be displayed. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------------------------------| ---- |--------------------------------------| +| type | string | Yes | Event type. The value is fixed at `avoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | Yes | Callback used to return the area and area type.| + +**Example** + +```js +windowClass.on('avoidAreaChange', (type, data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. type:' + JSON.stringify(type) + 'Data: ' + JSON.stringify(data)); +}); +``` + +### off('avoidAreaChange')9+ + +off(type: 'avoidAreaChange', callback: Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}>): void + +Disables listening for changes to the area where the window cannot be displayed. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- |-----------------------------------------------------------------------------|-----|------------------------------------| +| type | string | Yes | Event type. The value is fixed at `avoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | No | Callback used to return the area and area type.| + +**Example** + +```js +windowClass.off('avoidAreaChange'); +``` ### on('keyboardHeightChange')7+ @@ -1470,19 +1886,18 @@ Enables listening for keyboard height changes. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **keyboardHeightChange**, indicating the keyboard height change event.| -| callback | Callbacknumber> | Yes | Callback used to return the information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| +| callback | Callback { - console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); - }); - ``` +```js +windowClass.on('keyboardHeightChange', (data) => { + console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); +}); +``` ### off('keyboardHeightChange')7+ @@ -1496,15 +1911,60 @@ Disables listening for keyboard height changes. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **keyboardHeightChange**, indicating the keyboard height change event.| -| callback | Callback<number> | No | Callback used to return the information. | +| type | string | Yes | Event type. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| +| callback | Callback<number> | No | Callback used to return the current keyboard height. | + +**Example** + +```js +windowClass.off('keyboardHeightChange'); +``` + +### on('touchOutside')9+ + +on(type: 'touchOutside', callback: Callback<void>): void + +Enables listening for click events outside this window. +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at `touchOutside`, indicating the click event outside this window.| +| callback | Callback { + console.info('touch outside'); +}); +``` + +### off('touchOutside')9+ + +off(type: 'touchOutside', callback?: Callback<void>): void + +Disables listening for click events outside this window. +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at `touchOutside`, indicating the click event outside this window.| +| callback | Callback<number> | No | Callback used to Callback used to return the click event outside this window. | **Example** - ```js - var type = 'keyboardHeightChange'; - windowClass.off(type); - ``` +```js +windowClass.off('touchOutside'); +``` ### isSupportWideGamut8+ @@ -1516,21 +1976,21 @@ Checks whether this window supports the wide color gamut mode. This API uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the wide color gamut mode is supported.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that the wide color gamut mode is supported, and `false` means the opposite.| **Example** - ```js - windowClass.isSupportWideGamut((err, data) => { - if (err.code) { - console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)) - }) - ``` +```js +windowClass.isSupportWideGamut((err, data) => { + if (err.code) { + console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); +}) +``` ### isSupportWideGamut8+ @@ -1544,18 +2004,18 @@ Checks whether this window supports the wide color gamut mode. This API uses a p | Type | Description | | ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return whether the wide color gamut mode is supported.| +| Promise<boolean> | Promise used to return the result. The value `true` means that the wide color gamut mode is supported, and `false` means the opposite.| **Example** - ```js - let promise = windowClass.isSupportWideGamut(); - promise.then((data)=> { - console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.isSupportWideGamut(); +promise.then((data)=> { + console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); +}); +``` ### setColorSpace8+ @@ -1570,19 +2030,19 @@ Sets this window to the wide or default color gamut mode. This API uses an async | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ------------ | | colorSpace | [ColorSpace](#colorspace) | Yes | Color gamut mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err, data) => { - if (err.code) { - console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)) - }) - ``` +```js +windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err, data) => { + if (err.code) { + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)); +}) +``` ### setColorSpace8+ @@ -1594,26 +2054,26 @@ Sets this window to the wide or default color gamut mode. This API uses a promis **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------ | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | -------------- | | colorSpace | [ColorSpace](#colorspace) | Yes | Color gamut mode.| **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.isSupportWideGamut(window.ColorSpace.WIDE_GAMUT); - promise.then((data)=> { - console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT); +promise.then((data)=> { + console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); +}); +``` ### getColorSpace8+ @@ -1625,21 +2085,21 @@ Obtains the color gamut mode of this window. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------- | ---- | -------------------------- | -| callback | AsyncCallback<[ColorSpace](#colorspace)> | Yes | Callback used to return the color gamut mode obtained.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ---------------------------------------------------------- | +| callback | AsyncCallback<[ColorSpace](#colorspace)> | Yes | Callback used to return the result. When the color gamut mode is obtained successfully, `err` is `undefined`, and `data` is the current color gamut mode.| **Example** - ```js - windowClass.getColorSpace((err, data) => { - if (err.code) { - console.error('Failed to get window colorspace. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data)) - }) - ``` +```js +windowClass.getColorSpace((err, data) => { + if (err.code) { + console.error('Failed to get window colorspace. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data)); +}) +``` ### getColorSpace8+ @@ -1651,26 +2111,26 @@ Obtains the color gamut mode of this window. This API uses a promise to return t **Return value** -| Type | Description | -| ---------------------------------------- | ----------------------------------------- | -| Promise<[ColorSpace](#colorspace)> | Promise used to return the color gamut mode obtained.| +| Type | Description | +| ---------------------------------------- | ------------------------------- | +| Promise<[ColorSpace](#colorspace)> | Promise used to return the current color gamut mode.| **Example** - ```js - let promise = windowClass.getColorSpace(); - promise.then((data)=> { - console.info('Succeeded in getting window color space. Cause:' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to get window colorspace. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.getColorSpace(); +promise.then((data)=> { + console.info('Succeeded in getting window color space. Cause:' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to get window colorspace. Cause: ' + JSON.stringify(err)); +}); +``` ### setBackgroundColor setBackgroundColor(color: string, callback: AsyncCallback<void>): void -Sets the background color for this window. This API uses an asynchronous callback to return the result. +Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9). **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1678,27 +2138,27 @@ Sets the background color for this window. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var color = '#00ff33'; - windowClass.setBackgroundColor(color, (err, data) => { - if (err.code) { - console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); - }); - ``` +```js +var color = '#00ff33'; +windowClass.setBackgroundColor(color, (err, data) => { + if (err.code) { + console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); +}); +``` ### setBackgroundColor setBackgroundColor(color: string): Promise<void> -Sets the background color for this window. This API uses a promise to return the result. +Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9). **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1706,25 +2166,25 @@ Sets the background color for this window. This API uses a promise to return the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| +| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var color = '#00ff33'; - let promise = windowClass.setBackgroundColor(color); - promise.then((data)=> { - console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var color = '#00ff33'; +let promise = windowClass.setBackgroundColor(color); +promise.then((data)=> { + console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); +}); +``` ### setBrightness @@ -1738,21 +2198,21 @@ Sets the screen brightness for this window. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var brightness = 1; - windowClass.setBrightness(brightness, (err, data) => { - if (err.code) { - console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); - }); - ``` +```js +var brightness = 1; +windowClass.setBrightness(brightness, (err, data) => { + if (err.code) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); +}); +``` ### setBrightness @@ -1766,25 +2226,25 @@ Sets the screen brightness for this window. This API uses a promise to return th | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var brightness = 1; - let promise = windowClass.setBrightness(brightness); - promise.then((data)=> { - console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var brightness = 1; +let promise = windowClass.setBrightness(brightness); +promise.then((data)=> { + console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); +}); +``` ### setDimBehind(deprecated) @@ -1794,7 +2254,7 @@ Sets the dimness of the window that is not on top. This API uses an asynchronous > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1802,20 +2262,20 @@ Sets the dimness of the window that is not on top. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------------- | ------------------------- | ---- | -------------------------------------------------- | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value `1` indicates the dimmest.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - windowClass.setDimBehind(0.5, (err, data) => { - if (err.code) { - console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the dimness. Data:' + JSON.stringify(data)); - }); - ``` +```js +windowClass.setDimBehind(0.5, (err, data) => { + if (err.code) { + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the dimness. Data:' + JSON.stringify(data)); +}); +``` ### setDimBehind(deprecated) @@ -1825,7 +2285,7 @@ Sets the dimness of the window that is not on top. This API uses a promise to re > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1833,24 +2293,24 @@ Sets the dimness of the window that is not on top. This API uses a promise to re | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | -------------------------------------------------- | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest.| +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value `1` indicates the dimmest.| **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.setDimBehind(0.5); - promise.then((data)=> { - console.info('Succeeded in setting the dimness. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.setDimBehind(0.5); +promise.then((data)=> { + console.info('Succeeded in setting the dimness. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); +}); +``` ### setFocusable7+ @@ -1865,20 +2325,20 @@ Sets whether this window can gain focus. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | ----------- | ------------------------- | ---- | ---------------------------- | | isFocusable | boolean | Yes | Whether the window can gain focus.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var isFocusable= true; - windowClass.setFocusable(isFocusable, (err, data) => { - if (err.code) { - console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); - }); - ``` +```js +var isFocusable= true; +windowClass.setFocusable(isFocusable, (err, data) => { + if (err.code) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); +}); +``` ### setFocusable7+ @@ -1896,21 +2356,21 @@ Sets whether this window can gain focus. This API uses a promise to return the r **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var isFocusable= true; - let promise = windowClass.setFocusable(isFocusable); - promise.then((data)=> { - console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var isFocusable= true; +let promise = windowClass.setFocusable(isFocusable); +promise.then((data)=> { + console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); +}); +``` ### setKeepScreenOn @@ -1925,20 +2385,52 @@ Sets whether to keep the screen always on. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------------- | ------------------------- | ---- | ------------------------ | | isKeepScreenOn | boolean | Yes | Whether to keep the screen always on.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +var isKeepScreenOn = true; +windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => { + if (err.code) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); +}); +``` + +### setKeepScreenOn + +setKeepScreenOn(isKeepScreenOn: boolean): Promise<void> + +Sets whether to keep the screen always on. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------- | ---- | ------------------------ | +| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var isKeepScreenOn = true; - windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => { - if (err.code) { - console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); - }); - ``` +```js +var isKeepScreenOn = true; +let promise = windowClass.setKeepScreenOn(isKeepScreenOn); +promise.then((data) => { + console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); +}); +``` ### setOutsideTouchable(deprecated) @@ -1948,7 +2440,7 @@ Sets whether the area outside the subwindow is touchable. This API uses an async > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1956,20 +2448,20 @@ Sets whether the area outside the subwindow is touchable. This API uses an async | Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | ---------------- | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means that such an area is touchable, and **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value `true` means that such an area is touchable, and `false` means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - windowClass.setOutsideTouchable(true, (err, data) => { - if (err.code) { - console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)) - }) - ``` +```js +windowClass.setOutsideTouchable(true, (err, data) => { + if (err.code) { + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)); +}) +``` ### setOutsideTouchable(deprecated) @@ -1979,7 +2471,7 @@ Sets whether the area outside the subwindow is touchable. This API uses a promis > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1987,56 +2479,24 @@ Sets whether the area outside the subwindow is touchable. This API uses a promis | Name | Type | Mandatory| Description | | --------- | ------- | ---- | ---------------- | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means that such an area is touchable, and **false** means the opposite.| +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value `true` means that such an area is touchable, and `false` means the opposite.| **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - let promise = windowClass.setOutsideTouchable(true); - promise.then((data)=> { - console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); - }); - ``` - -### setKeepScreenOn - -setKeepScreenOn(isKeepScreenOn: boolean): Promise<void> - -Sets whether to keep the screen always on. This API uses a promise to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ------- | ---- | ------------------------ | -| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on.| - -**Return value** - -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| - -**Example** - - ```js - var isKeepScreenOn= true; - let promise = windowClass.setKeepScreenOn(isKeepScreenOn); - promise.then((data)=> { - console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = windowClass.setOutsideTouchable(true); +promise.then((data)=> { + console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); +}); +``` ### setPrivacyMode7+ @@ -2051,21 +2511,21 @@ Sets whether this window is in privacy mode. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | ------------- | ------------------------- | ---- | -------------------- | | isPrivacyMode | boolean | Yes | Whether the window is in privacy mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var isPrivacyMode = true; - windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { - if (err.code) { - console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window to privacy mode. Data:' + JSON.stringify(data)); - - }); - ``` +```js +var isPrivacyMode = true; +windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { + if (err.code) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to privacy mode. Data:' + JSON.stringify(data)); + +}); +``` ### setPrivacyMode7+ @@ -2083,21 +2543,21 @@ Sets whether this window is in privacy mode. This API uses a promise to return t **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var isPrivacyMode = true; - let promise = windowClass.setPrivacyMode(isPrivacyMode); - promise.then((data)=> { - console.info('Succeeded in setting the window to privacy mode. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var isPrivacyMode = true; +let promise = windowClass.setPrivacyMode(isPrivacyMode); +promise.then((data)=> { + console.info('Succeeded in setting the window to privacy mode. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); +}); +``` ### setTouchable7+ @@ -2112,21 +2572,21 @@ Sets whether this window is touchable. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | ----------- | ------------------------- | ---- | -------------------- | | isTouchable | boolean | Yes | Whether the window is touchable.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js - var isTouchable = true; - windowClass.setTouchable(isTouchable, (err, data) => { - if (err.code) { - console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window to be touchable. Data:' + JSON.stringify(data)); - - }); - ``` +```js +var isTouchable = true; +windowClass.setTouchable(isTouchable, (err, data) => { + if (err.code) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be touchable. Data:' + JSON.stringify(data)); + +}); +``` ### setTouchable7+ @@ -2144,30 +2604,97 @@ Sets whether this window is touchable. This API uses a promise to return the res **Return value** -| Type | Description | -| ------------------- | ----------------------------------------------- | -| Promise<void> | Promise used to return the execution result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var isTouchable = true; - let promise = windowClass.setTouchable(isTouchable); - promise.then((data)=> { - console.info('Succeeded in setting the window to be touchable. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); - }); - ``` +```js +var isTouchable = true; +let promise = windowClass.setTouchable(isTouchable); +promise.then((data)=> { + console.info('Succeeded in setting the window to be touchable. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); +}); +``` + +### setForbidSplitMove9+ + +setForbidSplitMove(isForbidSplitMove: boolean, callback: AsyncCallback<void>): void + +Sets whether this window is forbidden to move in split-screen mode. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +var isForbidSplitMove = true; +windowClass.setForbidSplitMove(isForbidSplitMove, (err, data) => { + if (err.code) { + console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in forbidding window moving in split screen mode. Data:' + JSON.stringify(data)); + +}); +``` + +### setForbidSplitMove9+ + +setForbidSplitMove(isForbidSplitMove: boolean): Promise<void> + +Sets whether this window is forbidden to move in split-screen mode. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | -------------------- | +| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +var isForbidSplitMove = true; +let promise = windowClass.setForbidSplitMove(isForbidSplitMove); +promise.then((data)=> { + console.info('Succeeded in forbidding window moving in split screen mode. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to forbidd window moving in split screen mode. Cause: ' + JSON.stringify(err)); +}); +``` ## WindowStageEventType9+ Describes the lifecycle of a window stage. +This API can be used only in the stage model. + **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value | Description | -| ---------- | ------ | -------- | +| Name | Default Value | Description | +| ---------- | ------ | ---------- | | FOREGROUND | 1 | The window stage is running in the foreground.| | ACTIVE | 2 | The window stage gains focus.| | INACTIVE | 3 | The window stage loses focus.| @@ -2175,79 +2702,124 @@ Describes the lifecycle of a window stage. ## WindowStage9+ -Before calling any of the following APIs, you must use `[onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate)` to create a **WindowStage** instance. +Implements a window manager, which manages each basic window unit, that is, [Window](#window) instance. + +Before calling any of the following APIs, you must use `[onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate)` to create a `WindowStage` instance. + +### getMainWindow9+ + +getMainWindow(callback: AsyncCallback<Window>): void + +Obtains the main window of this window stage. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | --------------------------------------------- | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window.| + +**Example** +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + var windowClass = null; + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); + }); + } +} +``` ### getMainWindow9+ getMainWindow(): Promise<Window> Obtains the main window of this window stage. This API uses a promise to return the result. +This API can be used only in the stage model. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| -------------------------------- | ---------------------------------------------------------- | +| Type | Description | +| -------------------------------- | ------------------------------------------------ | | Promise<[Window](#window)> | Promise used to return the main window.| **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - let promise = windowStage.getMainWindow(); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); - }); - } - } - ``` +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + var windowClass = null; + let promise = windowStage.getMainWindow(); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); + }); + } +} +``` +### createSubWindow9+ -### getMainWindow9+ +createSubWindow(name: string, callback: AsyncCallback<Window>): void -getMainWindow(callback: AsyncCallback<Window>): void +Creates a subwindow for this window stage. This API uses an asynchronous callback to return the result. -Obtains the main window of this window stage. This API uses an asynchronous callback to return the result. +This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | --------------------------------------- | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | --------------------------------------------- | +| name | String | Yes | Name of the subwindow. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow.| **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); - }); - } - } - ``` - +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + var windowClass = null; + windowStage.createSubWindow("mySubWindow", (err, data) => { + if (err.code) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); + }); + } +} +``` ### createSubWindow9+ createSubWindow(name: string): Promise<Window> Creates a subwindow for this window stage. This API uses a promise to return the result. +This API can be used only in the stage model. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -2258,159 +2830,215 @@ Creates a subwindow for this window stage. This API uses a promise to return the **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the subwindow created.| +| Type | Description | +| -------------------------------- | ------------------------------------------------ | +| Promise<[Window](#window)> | Promise used to return the subwindow.| **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - let promise = windowStage.createSubWindow("mySubWindow"); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in create sub window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to create sub window. Cause: ' + JSON.stringify(err)); - }) - } - } - ``` +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + var windowClass = null; + let promise = windowStage.createSubWindow("mySubWindow"); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); + }) + } +} +``` +### getSubWindow9+ -### createSubWindow9+ +getSubWindow(callback: AsyncCallback<Array<Window>>): void -createSubWindow(name: string, callback: AsyncCallback<Window>): void +Obtains all the subwindows of this window stage. This API uses an asynchronous callback to return the result. -Creates a subwindow for this window stage. This API uses an asynchronous callback to return the result. +This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------ | -| name | String | Yes | Name of the subwindow. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------- | +| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows.| **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - windowStage.createSubWindow("mySubWindow", (err, data) => { - if (err.code) { - console.error('Failed to create sub window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in create sub window. Data: ' + JSON.stringify(data)); - windowClass.resetSize(500, 1000); - }); - } - } - ``` - +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + var windowClass = null; + windowStage.getSubWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data)); + }); + } +} +``` ### getSubWindow9+ getSubWindow(): Promise<Array<Window>> Obtains all the subwindows of this window stage. This API uses a promise to return the result. +This API can be used only in the stage model. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| --------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| --------------------------------------------- | ---------------------------------------------------- | | Promise<Array<[Window](#window)>> | Promise used to return all the subwindows.| **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - let promise = windowStage.getSubWindow(); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the sub window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to obtain the sub window. Cause: ' + JSON.stringify(err)); - }) - } - } - ``` +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + var windowClass = null; + let promise = windowStage.getSubWindow(); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to obtain the subwindow. Cause: ' + JSON.stringify(err)); + }) + } +} +``` +### loadContent9+ -### getSubWindow9+ +loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void -getSubWindow(callback: AsyncCallback<Array<Window>>): void +Loads content from a page associated with a local storage to the main window in this window stage. This API uses an asynchronous callback to return the result. -Obtains all the subwindows of this window stage. This API uses an asynchronous callback to return the result. +This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------- | -| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - windowStage.getSubWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the sub window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the sub window. Data: ' + JSON.stringify(data)); - }); - } - } - ``` +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + storage : LocalStorage + onWindowStageCreate(windowStage) { + this.storage = new LocalStorage(); + this.storage.setOrCreate("storageSimpleProp",121); + console.log('onWindowStageCreate'); + windowStage.loadContent("pages/page2",this.storage,(err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + }); + } +} +``` + +### loadContent9+ + +loadContent(path: string, storage?: LocalStorage): Promise<void> + +Loads content from a page associated with a local storage to the main window in this window stage. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | LocalStorage | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + storage : LocalStorage + onWindowStageCreate(windowStage) { + this.storage = new LocalStorage(); + this.storage.setOrCreate("storageSimpleProp",121); + console.log('onWindowStageCreate'); + var windowClass = null; + let promise = windowStage.loadContent("pages/page2",this.storage); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + }) + } +} +``` ### loadContent9+ loadContent(path: string, callback: AsyncCallback<void>): void -Loads content to this window stage. This API uses an asynchronous callback to return the result. +Loads content from a page to this window stage. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. -**System capability**: SystemCapability.WindowManager.WindowManager.Coretype with the value **windowSizeChange** +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------- | | path | string | Yes | Path of the page from which the content will be loaded.| -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result. | - -**Example** - - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - windowStage.loadContent("pages/page2", (err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) - }); - } - } - ``` +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + windowStage.loadContent("pages/page2", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + }); + } +} +``` ### on('windowStageEvent')9+ @@ -2418,28 +3046,30 @@ on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType> Enables listening for window stage lifecycle changes. +This API can be used only in the stage model. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **windowStageEvent**, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the information. | +| type | string | Yes | Event type. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var type = 'windowStageEvent'; - windowStage.on(type, (data) => { - console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + JSON.stringify(data)); - }); - } - } - ``` +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + windowStage.on('windowStageEvent', (data) => { + console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + JSON.stringify(data)); + }); + } +} +``` ### off('windowStageEvent')9+ @@ -2447,33 +3077,61 @@ off(eventType: 'windowStageEvent', callback?: Callback<WindowStageEventType&g Disables listening for window stage lifecycle changes. +This API can be used only in the stage model. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at **windowStageEvent**, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the information. | +| type | string | Yes | Event type. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | **Example** - ```ts - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var type = 'windowStageEvent'; - windowStage.off(type); - } - } - ``` +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + windowStage.off('windowStageEvent'); + } +} +``` + +### disableWindowDecor()9+ + +disableWindowDecor(): void + +Disables window decorators. -### setShowOnLockScreen('showOnLockScreen')9+ +This type can be used only in the stage model. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Example** + +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('disableWindowDecor'); + windowStage.disableWindowDecor(); + } +} +``` + +### setShowOnLockScreen()9+ setShowOnLockScreen(showOnLockScreen: boolean): void Sets whether to display the window of the application on the lock screen. +This API can be used only in the stage model. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -2485,6 +3143,7 @@ Sets whether to display the window of the application on the lock screen. **Example** ```ts +import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125174.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125174.png new file mode 100644 index 0000000000000000000000000000000000000000..f1abe2afcb7902557ac3c4f58abfdf333af03121 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125174.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125178.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125178.png new file mode 100644 index 0000000000000000000000000000000000000000..6064f64867e3aca621244e1e6fdb16d3ab2ed748 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125178.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125180.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125180.png new file mode 100644 index 0000000000000000000000000000000000000000..7cc96f8f6364b93923f0a88b895fe6b151080932 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125180.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125184.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125184.png new file mode 100644 index 0000000000000000000000000000000000000000..ecf361e4c749446160da1e8a07169b21d99f362a Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125184.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125188.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125188.png new file mode 100644 index 0000000000000000000000000000000000000000..44e4d991524bd0ef88a0dd10f204e022dd9d0621 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125188.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125190.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125190.png new file mode 100644 index 0000000000000000000000000000000000000000..5e23c304c4911dc0ef487dfeb8d7820aea5fb44b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125190.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125194.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125194.png new file mode 100644 index 0000000000000000000000000000000000000000..e370a44cf043fc34bd8891f57faad2cd2ca05707 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125194.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125210.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125210.png new file mode 100644 index 0000000000000000000000000000000000000000..a59bc9cdb0f75ad79e4714d3593216021369c862 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125210.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125214.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125214.png new file mode 100644 index 0000000000000000000000000000000000000000..b3c353b6a872d3597b767f4c216b2d16bfc2139b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125214.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125216.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125216.png new file mode 100644 index 0000000000000000000000000000000000000000..664d13c38389361e61a45870899e2a6f0bfc835f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125216.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125218.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125218.png new file mode 100644 index 0000000000000000000000000000000000000000..1b0ed50716d897398c1e9a741e08ff5f1b9fd9de Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125218.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125222.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125222.png new file mode 100644 index 0000000000000000000000000000000000000000..2dadb92ce56793e2dd693bfa7d99b0c1168130dc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125222.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125224.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125224.png new file mode 100644 index 0000000000000000000000000000000000000000..41be1a646e14511b5d177d11a7bce10deaee5bc9 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125224.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125226.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125226.png new file mode 100644 index 0000000000000000000000000000000000000000..2dadb92ce56793e2dd693bfa7d99b0c1168130dc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125226.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125228.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125228.png new file mode 100644 index 0000000000000000000000000000000000000000..515185ab1b3cf9aaba1204760dae19ab3c112b42 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125228.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125230.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125230.png new file mode 100644 index 0000000000000000000000000000000000000000..984e7a561e661ecefca8b60d5ac239b67f96c98c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125230.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125232.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125232.png new file mode 100644 index 0000000000000000000000000000000000000000..115cb4c96382681743381aeba099549dc24c2ae5 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125232.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125234.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125234.png new file mode 100644 index 0000000000000000000000000000000000000000..af32ecea68c1cef693bcfa379af5ac28f66c1e14 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125234.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125236.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125236.png new file mode 100644 index 0000000000000000000000000000000000000000..63a8c6adc29d340634ed06a1006a0fb56c991a9d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125236.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125238.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125238.png new file mode 100644 index 0000000000000000000000000000000000000000..dfcb0c5e259b3f8d7375c21712249c1e847edd67 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125238.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125240.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125240.png new file mode 100644 index 0000000000000000000000000000000000000000..a9aba5f67b94427168fade014542532431e28a2e Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125240.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125242.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125242.png new file mode 100644 index 0000000000000000000000000000000000000000..5c5e360f249a2002ba68ad9b94bd7f66f5d6aab1 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125242.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125244.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125244.png new file mode 100644 index 0000000000000000000000000000000000000000..0d386fef5c4fa9faf1b29c7667c7392db250f2eb Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125244.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125246.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125246.png new file mode 100644 index 0000000000000000000000000000000000000000..7dfc7ee8793298d19c939369ba980abd547982ff Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125246.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125248.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125248.png new file mode 100644 index 0000000000000000000000000000000000000000..4b1948de8581602c6c5879c03d68c14f06eccd00 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125248.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125250.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125250.png new file mode 100644 index 0000000000000000000000000000000000000000..5d0ae86ad14ff863511a10ecc1a85b273e826dfc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125250.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125254.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125254.png new file mode 100644 index 0000000000000000000000000000000000000000..309d1c46f8bc396df5eaed381a5ffa2f0389d602 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125254.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125256.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125256.png new file mode 100644 index 0000000000000000000000000000000000000000..02d5f4e31b020ea9f64e36a7b7cd50299cf3d7f2 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125256.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125258.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125258.png new file mode 100644 index 0000000000000000000000000000000000000000..e9a0799a203fdd7bd41fa5175585dc170a20156e Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125258.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125260.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125260.png new file mode 100644 index 0000000000000000000000000000000000000000..ac66614c0f277cd722b3d090cb10efb973152b0f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125260.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125262.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125262.png new file mode 100644 index 0000000000000000000000000000000000000000..131584c72c082f40e2b466e2706c86a05df375e0 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125262.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284968.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284968.png new file mode 100644 index 0000000000000000000000000000000000000000..c0df3f4f7d99f0b8c39995133c71d944bc07ea4b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284968.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284970.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284970.png new file mode 100644 index 0000000000000000000000000000000000000000..1c4f9ae52153198f8690a1066fe66ba8c7bd1ee1 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284970.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284972.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284972.png new file mode 100644 index 0000000000000000000000000000000000000000..69cb300d4bc8decee06c7fb64b03a24287865a8f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284972.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284974.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284974.png new file mode 100644 index 0000000000000000000000000000000000000000..0a5eb251a8d731dc6a9d8b1f31f904c42fd372c3 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284974.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284976.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284976.png new file mode 100644 index 0000000000000000000000000000000000000000..ac0521001d2513fd69e48ce61e1d1128b9d3a6dd Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284976.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284980.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284980.png new file mode 100644 index 0000000000000000000000000000000000000000..4e41450db5d70f6d10d6d7bf59daba33085c177e Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284980.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284982.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284982.png new file mode 100644 index 0000000000000000000000000000000000000000..6e4476c4791e37d4681f8e12313ae1cad0887c1b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284982.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284990.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284990.png new file mode 100644 index 0000000000000000000000000000000000000000..4c4c304b67c398f32c5fff516cdde377ca39c73d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284990.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284992.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284992.png new file mode 100644 index 0000000000000000000000000000000000000000..6dc88e656c293c2e65939e4a793684488dfc81be Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284992.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284996.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284996.png new file mode 100644 index 0000000000000000000000000000000000000000..e72165fdf1b24d80f0abde742ad3d848497c6ea7 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284996.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284998.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284998.png new file mode 100644 index 0000000000000000000000000000000000000000..57594c6855d4cdf1b37cc3e5354374c9dae0823b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284998.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285000.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285000.png new file mode 100644 index 0000000000000000000000000000000000000000..c89f746719790333bce2bde8c5b8d86102fdfc33 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285000.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285002.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285002.png new file mode 100644 index 0000000000000000000000000000000000000000..8bc3583f82d21c8bec0c70b2da36ed05723fd9a7 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285002.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285006.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285006.png new file mode 100644 index 0000000000000000000000000000000000000000..891d52276622fd51893634ce26e08bd56f62b782 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285006.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285010.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285010.png new file mode 100644 index 0000000000000000000000000000000000000000..8b3eec4e46f6a29dc47694940ceaef1cfa1314af Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285010.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285012.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285012.png new file mode 100644 index 0000000000000000000000000000000000000000..45467f3e6fc0866b6da0521911bdb5e7d740df29 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285012.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285014.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285014.png new file mode 100644 index 0000000000000000000000000000000000000000..8e195633945b3387c46a7d295862351d4ff1fc64 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285014.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285016.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285016.png new file mode 100644 index 0000000000000000000000000000000000000000..cbc1d312680f479e8c443476ea39eaf1e8a16e55 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285016.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285018.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285018.png new file mode 100644 index 0000000000000000000000000000000000000000..1324b43b3f5b8dd0548cf2069c4c532c5284c445 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285018.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285020.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285020.png new file mode 100644 index 0000000000000000000000000000000000000000..481c833482d38c5f564127c8f412fe3c0275fd24 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285020.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285022.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285022.png new file mode 100644 index 0000000000000000000000000000000000000000..1072a50f468dda3c90c889c31424b7c290eb1a13 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285022.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285026.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285026.png new file mode 100644 index 0000000000000000000000000000000000000000..0d53a47b7eace81d5c7da88c59fee61e30c89681 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285026.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285028.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285028.png new file mode 100644 index 0000000000000000000000000000000000000000..f1abe2afcb7902557ac3c4f58abfdf333af03121 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285028.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285030.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285030.png new file mode 100644 index 0000000000000000000000000000000000000000..64fdda07447707816e8a6238939169f58a4ce58f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285030.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285032.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285032.png new file mode 100644 index 0000000000000000000000000000000000000000..4e41c2cd90ba17798448d70b493ccceb3ac960f0 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285032.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285038.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285038.png new file mode 100644 index 0000000000000000000000000000000000000000..6eb2d41877c85cccfb918b042bc13c81c58ec191 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285038.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285040.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285040.png new file mode 100644 index 0000000000000000000000000000000000000000..2e7cec00f9d186d76ff5cb12d47811084217cc1c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285040.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285042.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285042.png new file mode 100644 index 0000000000000000000000000000000000000000..daa035cea33b810571c18de67e4ac887eeb11850 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285042.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285044.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285044.png new file mode 100644 index 0000000000000000000000000000000000000000..6823cbc9203b07abae455b4ee5c7692878c4be72 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285044.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285046.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285046.png new file mode 100644 index 0000000000000000000000000000000000000000..ca1edf2219980ab9c8533b9fda3219521c50533d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285046.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285048.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285048.png new file mode 100644 index 0000000000000000000000000000000000000000..bf38fe45eaf254939b88b9d2a66635408060acf7 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285048.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285050.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285050.png new file mode 100644 index 0000000000000000000000000000000000000000..3e6aaacfe1c26157294e6dedfeaa1488aeed12a3 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285050.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285052.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285052.png new file mode 100644 index 0000000000000000000000000000000000000000..6823cbc9203b07abae455b4ee5c7692878c4be72 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285052.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285054.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285054.png new file mode 100644 index 0000000000000000000000000000000000000000..dfcb0c5e259b3f8d7375c21712249c1e847edd67 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285054.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285056.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285056.png new file mode 100644 index 0000000000000000000000000000000000000000..9114031e04fc28be59e8c9567c0fcfe81a9cc5cb Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285056.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285058.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285058.png new file mode 100644 index 0000000000000000000000000000000000000000..6f085565bd8c64d44bf58ce0969557515ec7ab97 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285058.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285060.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285060.png new file mode 100644 index 0000000000000000000000000000000000000000..93825b7fe53a0794751ee4aa3ca46300c404835e Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285060.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285062.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285062.png new file mode 100644 index 0000000000000000000000000000000000000000..c0b21ed6b44c2f756458137f931873f540c16e5f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285062.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285064.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285064.png new file mode 100644 index 0000000000000000000000000000000000000000..b80a6c31cdb287c35965c7841aa97711d79b371c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285064.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285066.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285066.png new file mode 100644 index 0000000000000000000000000000000000000000..bca655617699ef8dc1265bf692a3170c7effe15b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285066.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285068.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285068.png new file mode 100644 index 0000000000000000000000000000000000000000..8a5c7039b580128e75299672dc5438151dcf3572 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285068.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285070.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285070.png new file mode 100644 index 0000000000000000000000000000000000000000..12085848c0f6472d53f7e6504c1924ea6f5a44c1 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285070.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164835.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164835.png new file mode 100644 index 0000000000000000000000000000000000000000..53081e06f458cfc1772de30f669180333b8d783d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164835.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164837.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164837.png new file mode 100644 index 0000000000000000000000000000000000000000..a33c4fce8448e2127b21e277437195ce0002766b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164837.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164841.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164841.png new file mode 100644 index 0000000000000000000000000000000000000000..b234a769d1a9f1f30c4d2127160cf067e9f71ad6 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164841.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164843.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164843.png new file mode 100644 index 0000000000000000000000000000000000000000..3ca3e045717379bb09fa8d13ea0d42019bf546f2 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164843.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164849.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164849.png new file mode 100644 index 0000000000000000000000000000000000000000..069f570291be858a1768b75719a4a6adbd1bdef8 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164849.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164851.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164851.png new file mode 100644 index 0000000000000000000000000000000000000000..c33d763d18f5108bf0eedba19c662d05af397ee9 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164851.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164855.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164855.png new file mode 100644 index 0000000000000000000000000000000000000000..fe422eecde9ec9f1fcac762bd81a23b3fa3abde7 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164855.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164865.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164865.png new file mode 100644 index 0000000000000000000000000000000000000000..bc28f5056c679e189543c8ad6fba67fb56db7655 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164865.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164875.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164875.png new file mode 100644 index 0000000000000000000000000000000000000000..9ed54c6c5c5186fb43f24dab24f7689ae0d14a12 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164875.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164877.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164877.png new file mode 100644 index 0000000000000000000000000000000000000000..8442c9b2258c79ee6b6a3d5963df5b792bbb1a16 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164877.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164879.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164879.png new file mode 100644 index 0000000000000000000000000000000000000000..d77ed21418dc3035feb9f9c8e15815e577d71a90 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164879.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164885.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164885.png new file mode 100644 index 0000000000000000000000000000000000000000..9c43caf5fdfd466eafc37b793f509a6bde2b885d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164885.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164887.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164887.png new file mode 100644 index 0000000000000000000000000000000000000000..ff0aa71de78cb461a6602398ee915c677efdf3d4 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164887.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164889.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164889.png new file mode 100644 index 0000000000000000000000000000000000000000..04bcf099edface801be6074a33ff33a980c9b606 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164889.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164893.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164893.png new file mode 100644 index 0000000000000000000000000000000000000000..00767e63c899eec52c2c732e834bca8d26d348ce Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164893.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164895.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164895.png new file mode 100644 index 0000000000000000000000000000000000000000..7983d590a2c617c6cad68c90af6b12aa17518810 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164895.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164897.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164897.png new file mode 100644 index 0000000000000000000000000000000000000000..0ac129028e67b43fcae8e3d5c1a539cc45ba6d21 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164897.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164899.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164899.png new file mode 100644 index 0000000000000000000000000000000000000000..800bf296338fd01962f16a8863c37bfe515ce3be Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164899.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164901.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164901.png new file mode 100644 index 0000000000000000000000000000000000000000..d1d37504e15eb6fccd6b1c8e985d37fcc8ba9875 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164901.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164905.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164905.png new file mode 100644 index 0000000000000000000000000000000000000000..c88212b6818d6d18c77ee497cfcafaf661a70d52 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164905.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164907.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164907.png new file mode 100644 index 0000000000000000000000000000000000000000..6a64534a0a867d44cf81c8a34c9981b5fbaf5faf Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164907.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164909.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164909.png new file mode 100644 index 0000000000000000000000000000000000000000..6d795f1618b1546c94266548069eccf9e9af2e01 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164909.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164911.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164911.png new file mode 100644 index 0000000000000000000000000000000000000000..1072a50f468dda3c90c889c31424b7c290eb1a13 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164911.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164913.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164913.png new file mode 100644 index 0000000000000000000000000000000000000000..d62fc7767f7b2e0e8d0d7fed57e30bdf6a6a332f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164913.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164915.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164915.png new file mode 100644 index 0000000000000000000000000000000000000000..87915df37741dacfe9448bfebccf5a88d3ca2a76 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164915.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164917.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164917.png new file mode 100644 index 0000000000000000000000000000000000000000..bdb02fdda28a155e2f622eeea2ff820144780e50 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164917.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164921.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164921.png new file mode 100644 index 0000000000000000000000000000000000000000..39cf9d01563cf63bee003a47cd88258e860a0757 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164921.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164923.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164923.png new file mode 100644 index 0000000000000000000000000000000000000000..f89e20a55ba1e81f2cbda2bd0241edefadbe7149 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164923.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164925.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164925.png new file mode 100644 index 0000000000000000000000000000000000000000..a68e61ab120651294310c5e3632ce22d71917a52 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164925.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324699.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324699.gif new file mode 100644 index 0000000000000000000000000000000000000000..4731d53600aa7dced61e10ce21505a5086280edd Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324699.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324729.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324729.png new file mode 100644 index 0000000000000000000000000000000000000000..c25a692065d473ccf9f5b6d36254787e2497fad6 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324729.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324731.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324731.png new file mode 100644 index 0000000000000000000000000000000000000000..283cf90b3828b36af6fb3a746e806f6715053310 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324731.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324733.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324733.png new file mode 100644 index 0000000000000000000000000000000000000000..858c4187d3a2874f651adc09dcae9a32f8407d86 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324733.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324735.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324735.png new file mode 100644 index 0000000000000000000000000000000000000000..58293d5e874f2aa36ecaf7282ca9e4736318092f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324735.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324737.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324737.png new file mode 100644 index 0000000000000000000000000000000000000000..e863d7a1c3b9c1ca08bd182dce43c55a4866d59b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324737.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324739.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324739.png new file mode 100644 index 0000000000000000000000000000000000000000..486baf6be50982404fd1c68a5bc51db45c62046a Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324739.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324741.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324741.png new file mode 100644 index 0000000000000000000000000000000000000000..93299fc38d761e5251673210c364f6825e319153 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324741.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324743.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324743.png new file mode 100644 index 0000000000000000000000000000000000000000..0491d350277cd67d7774e3761164b9dd7038a117 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324743.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324745.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324745.png new file mode 100644 index 0000000000000000000000000000000000000000..b780eb08852e8916ec6ff1a401ea6946c8d727cf Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324745.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324747.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324747.png new file mode 100644 index 0000000000000000000000000000000000000000..b162dbf0a6c890a03ea1aa0b28bdb454651b697c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324747.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324755.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324755.png new file mode 100644 index 0000000000000000000000000000000000000000..454b1796715794d51e2a1a4649bfafa1bfde80f0 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324755.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324757.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324757.png new file mode 100644 index 0000000000000000000000000000000000000000..a618da21cf6c6d32066286e594921c0fc75b5dba Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324757.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324759.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324759.png new file mode 100644 index 0000000000000000000000000000000000000000..5e23c304c4911dc0ef487dfeb8d7820aea5fb44b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324759.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324761.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324761.png new file mode 100644 index 0000000000000000000000000000000000000000..91a276a7dffb4d98c507e9af6afa1912cca1fed2 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324761.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324767.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324767.png new file mode 100644 index 0000000000000000000000000000000000000000..6348bb2b6ee281976f7d58159e4c33db29f542ad Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324767.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324769.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324769.png new file mode 100644 index 0000000000000000000000000000000000000000..1821f9c40ad9d24dc10dc662ecbe7936c9e10633 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324769.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324771.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324771.png new file mode 100644 index 0000000000000000000000000000000000000000..5ee9f7e893611dce988b8aa7ccfe3fab4b9d912f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324771.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324773.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324773.png new file mode 100644 index 0000000000000000000000000000000000000000..21f20a4220aabf9449c707291633e7b3723fe378 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324773.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324775.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324775.png new file mode 100644 index 0000000000000000000000000000000000000000..adca00e684afb79ff4f21313d0586025576a8be1 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324775.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324777.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324777.png new file mode 100644 index 0000000000000000000000000000000000000000..c952585d8032733700b57ce1a919d71ce9a4b58b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324777.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324779.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324779.png new file mode 100644 index 0000000000000000000000000000000000000000..848454297b67eb73ab641424badc438433e24479 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324779.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324781.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324781.png new file mode 100644 index 0000000000000000000000000000000000000000..3621ef6876dbd1103487aed8ff190e6a0204ffde Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324781.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324785.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324785.png new file mode 100644 index 0000000000000000000000000000000000000000..6f5fe69b5a5a62b2d2b719b2be0a17a501363918 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324785.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324789.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324789.png new file mode 100644 index 0000000000000000000000000000000000000000..3e6aaacfe1c26157294e6dedfeaa1488aeed12a3 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324789.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324793.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324793.png new file mode 100644 index 0000000000000000000000000000000000000000..56db1024a714f821528656c64e12520311bae8f5 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324793.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324795.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324795.png new file mode 100644 index 0000000000000000000000000000000000000000..d87462d1cdc9410e91ee050a53d58e71d1c5f312 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324795.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324799.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324799.png new file mode 100644 index 0000000000000000000000000000000000000000..6f929d8ab35b708978d8053047cb56bec4fa83bc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324799.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324801.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324801.png new file mode 100644 index 0000000000000000000000000000000000000000..3fca22c329e9dc9ef73eee20757eac4ce7386842 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324801.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324803.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324803.png new file mode 100644 index 0000000000000000000000000000000000000000..378000d344e90ab4db41869a4612daf6b60d66ab Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324803.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324805.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324805.png new file mode 100644 index 0000000000000000000000000000000000000000..f89943fc98661a6d2b78b5659c41483308a0c54b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324805.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324807.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324807.png new file mode 100644 index 0000000000000000000000000000000000000000..d1ca7dd07fe7812ec1f87bf748595174569a5672 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324807.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324809.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324809.png new file mode 100644 index 0000000000000000000000000000000000000000..5b22707e37ec772dc08a961e557a937862210167 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324809.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324811.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324811.png new file mode 100644 index 0000000000000000000000000000000000000000..3026d3c195598159232b4b1f08e9f198f4b4fa2c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324811.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324813.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324813.png new file mode 100644 index 0000000000000000000000000000000000000000..51fb00e10bb5c167506ddfae1689b58e368df340 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324813.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324815.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324815.png new file mode 100644 index 0000000000000000000000000000000000000000..6e4476c4791e37d4681f8e12313ae1cad0887c1b Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324815.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324817.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324817.png new file mode 100644 index 0000000000000000000000000000000000000000..04ab7decab16cb7341665c2a67e8d5655a7eed6a Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324817.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324821.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324821.png new file mode 100644 index 0000000000000000000000000000000000000000..db83d39f98583ee653ee39b0237eb55961e539c7 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324821.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324823.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324823.png new file mode 100644 index 0000000000000000000000000000000000000000..56d32d4cd371c5374b133cb81c9c077aaf7b110d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324823.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324825.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324825.png new file mode 100644 index 0000000000000000000000000000000000000000..7cfd4846ca697424582edbfed23ed93ef9e98138 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324825.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324829.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324829.png new file mode 100644 index 0000000000000000000000000000000000000000..6315d4654d04dd6b9b295fa1f8b37e8c550b17cf Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324829.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324831.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324831.png new file mode 100644 index 0000000000000000000000000000000000000000..1e0bad2b2bfed2559e53a8bc21162e6163ec8434 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324831.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324833.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324833.png new file mode 100644 index 0000000000000000000000000000000000000000..0d22570503febc7a7dcba0d1e870f49f32fe489a Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324833.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324835.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324835.png new file mode 100644 index 0000000000000000000000000000000000000000..26f2f228b47b8acb8adcddc3abf9156d6c29364e Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324835.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324837.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324837.png new file mode 100644 index 0000000000000000000000000000000000000000..b54dbc2391d1a8f16312dd02dc3d65a35ea2626f Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324837.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324839.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324839.png new file mode 100644 index 0000000000000000000000000000000000000000..639f16f8aaf261176b3bc760c2eb616ad2f4aa28 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324839.png differ diff --git a/en/application-dev/reference/arkui-js/js-appendix-types.md b/en/application-dev/reference/arkui-js/js-appendix-types.md index 83e657a7e233893f13b5b11e0be51b2a3f581e95..b491d59c5fef5c948bf5119fcac48e302a83f3ff 100644 --- a/en/application-dev/reference/arkui-js/js-appendix-types.md +++ b/en/application-dev/reference/arkui-js/js-appendix-types.md @@ -1,1098 +1,167 @@ -# Type Attributes +# Type Attributes -## Length Type +## Length Type - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

length

-

string | number

-

Size unit. When the type is number, the unit is px. When the type is string, the pixel unit needs to be explicitly specified. Currently, the following pixel units are supported:

-
  • px: logical size unit.
  • fp6+: font size unit, which varies according to the system font size. Only text components support the setting of the font size.
-

percentage

-

string

-

Unit in percentage, for example, 50%.

-
+| Name | Type | Description | +| ---------- | -------------------------- | ---------------------------------------- | +| length | string \| number | Size unit. When the type is **number**, the unit is px. When the type is **string**, the pixel unit needs to be explicitly specified. Currently, the following pixel units are supported:
- **px**: logical size unit.
- **fp**6+: font size unit, which varies with the system font size. This unit is only available for text components.| +| percentage | string | Unit in percentage, for example, **50%**. | -## Color Type - - - - - - - - - - - -

Name

-

Type

-

Description

-

color

-

string | Color enumeration values

-

Color information.

-
The String format is as follows:
  • 'rgb(255, 255, 255)'
  • 'rgba(255, 255, 255, 1.0)'
  • HEX formats: #rrggbb and #aarrggbb
  • Enumeration format: 'black' and 'white'
    NOTE:

    The enumeration format is not supported in the JS script.

    -
    -
-
-
+## Color Type -**Table 1** Currently supported colors +| Name | Type | Description | +| ----- | --------------------- | ---------------------------------------- | +| color | string \|  color enums| Color information. The color enums are not supported in JavaScript scripts.
Available string formats are as follows:
- 'rgb(255, 255, 255)'
- 'rgba(255, 255, 255, 1.0)'
- HEX format: '\#rrggbb', '\#aarrggbb'
- Enumeration format: 'black','white'.| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Hexadecimal Code

-

Color

-

aliceblue

-

#f0f8ff

-

-

antiquewhite

-

#faebd7

-

-

aqua

-

#00ffff

-

-

aquamarine

-

#7fffd4

-

-

azure

-

#f0ffff

-

-

beige

-

#f5f5dc

-

-

bisque

-

#ffe4c4

-

-

black

-

#000000

-

-

blanchedalmond

-

#ffebcd

-

-

blue

-

#0000ff

-

-

blueviolet

-

#8a2be2

-

-

brown

-

#a52a2a

-

-

burlywood

-

#deB887

-

-

cadetblue

-

#5f9ea0

-

-

chartreuse

-

#7fff00

-

-

chocolate

-

#d2691e

-

-

coral

-

#ff7f50

-

-

cornflowerblue

-

#6495ed

-

-

cornsilk

-

#fff8dc

-

-

crimson

-

#dc143c

-

-

cyan

-

#00ffff

-

-

darkblue

-

#00008b

-

-

darkcyan

-

#008b8b

-

-

darkgoldenrod

-

#b8860b

-

-

darkgray

-

#a9a9a9

-

-

darkgreen

-

#006400

-

-

darkgrey

-

#a9a9a9

-

-

darkkhaki

-

#bdb76b

-

-

darkmagenta

-

#8b008b

-

-

darkolivegreen

-

#556b2f

-

-

darkorange

-

#ff8c00

-

-

darkorchid

-

#9932cc

-

-

darkred

-

#8b0000

-

-

darksalmon

-

#e9967a

-

-

darkseagreen

-

#8fbc8f

-

-

darkslateblue

-

#483d8b

-

-

darkslategray

-

#2f4f4f

-

-

darkslategrey

-

#2f4f4f

-

-

darkturquoise

-

#00ced1

-

-

darkviolet

-

#9400d3

-

-

deeppink

-

#ff1493

-

-

deepskyblue

-

#00bfff

-

-

dimgray

-

#696969

-

-

dimgrey

-

#696969

-

-

dodgerblue

-

#1e90ff

-

-

firebrick

-

#b22222

-

-

floralwhite

-

#fffaf0

-

-

forestgreen

-

#228b22

-

-

fuchsia

-

#ff00ff

-

-

gainsboro

-

#dcdcdc

-

-

ghostwhite

-

#f8f8ff

-

-

gold

-

#ffd700

-

-

goldenrod

-

#daa520

-

-

gray

-

#808080

-

-

green

-

#008000

-

-

greenyellow

-

#adff2f

-

-

grey

-

#808080

-

-

honeydew

-

#f0fff0

-

-

hotpink

-

#ff69b4

-

-

indianred

-

#cd5c5c

-

-

indigo

-

#4b0082

-

-

ivory

-

#fffff0

-

-

khaki

-

#f0e68c

-

-

lavender

-

#e6e6fa

-

-

lavenderblush

-

#fff0f5

-

-

lawngreen

-

#7cfc00

-

-

lemonchiffon

-

#fffacd

-

-

lightblue

-

#add8e6

-

-

lightcoral

-

#f08080

-

-

lightcyan

-

#e0ffff

-

-

lightgoldenrodyellow

-

#fafad2

-

-

lightgray

-

#d3d3d3

-

-

lightgreen

-

#90ee90

-

-

lightpink

-

#ffb6c1

-

-

lightsalmon

-

#ffa07a

-

-

lightseagreen

-

#20b2aa

-

-

lightskyblue

-

#87cefa

-

-

lightslategray

-

#778899

-

-

lightslategrey

-

#778899

-

-

lightsteelblue

-

#b0c4de

-

-

lightyellow

-

#ffffe0

-

-

lime

-

#00ff00

-

-

limegreen

-

#32cd32

-

-

linen

-

#faf0e6

-

-

magenta

-

#ff00ff

-

-

maroon

-

#800000

-

-

mediumaquamarine

-

#66cdaa

-

-

mediumblue

-

#0000cd

-

-

mediumorchid

-

#ba55d3

-

-

mediumpurple

-

#9370db

-

-

mediumseagreen

-

#3cb371

-

-

mediumslateblue

-

#7b68ee

-

-

mediumspringgreen

-

#00fa9a

-

-

mediumturquoise

-

#48d1cc

-

-

mediumvioletred

-

#c71585

-

-

midnightblue

-

#191970

-

-

mintcream

-

#f5fffa

-

-

mistyrose

-

#ffe4e1

-

-

moccasin

-

#ffe4b5

-

-

navajowhite

-

#ffdead

-

-

navy

-

#000080

-

-

oldlace

-

#fdf5e6

-

-

olive

-

#808000

-

-

olivedrab

-

#6b8e23

-

-

orange

-

#ffa500

-

-

orangered

-

#ff4500

-

-

orchid

-

#da70d6

-

-

palegoldenrod

-

#eee8aa

-

-

palegreen

-

#98fb98

-

-

paleturquoise

-

#afeeee

-

-

palevioletred

-

#db7093

-

-

papayawhip

-

#ffefd5

-

-

peachpuff

-

#ffdab9

-

-

peru

-

#cd853f

-

-

pink

-

#ffc0cb

-

-

plum

-

#dda0dd

-

-

powderblue

-

#b0e0e6

-

-

purple

-

#800080

-

-

rebeccapurple

-

#663399

-

-

red

-

#ff0000

-

-

rosybrown

-

#bc8f8f

-

-

royalblue

-

#4169e1

-

-

saddlebrown

-

#8b4513

-

-

salmon

-

#fa8072

-

-

sandybrown

-

#f4a460

-

-

seagreen

-

#2e8b57

-

-

seashell

-

#fff5ee

-

-

sienna

-

#a0522d

-

-

silver

-

#c0c0c0

-

-

skyblue

-

#87ceeb

-

-

slateblue

-

#6a5acd

-

-

slategray

-

#708090

-

-

slategrey

-

#708090

-

-

snow

-

#fffafa

-

-

springgreen

-

#00ff7f

-

-

steelblue

-

#4682b4

-

-

tan

-

#d2b48c

-

-

teal

-

#008080

-

-

thistle

-

#d8Bfd8

-

-

tomato

-

#ff6347

-

-

turquoise

-

#40e0d0

-

-

violet

-

#ee82ee

-

-

wheat

-

#f5deb3

-

-

white

-

#ffffff

-

-

whitesmoke

-

#f5f5f5

-

-

yellow

-

#ffff00

-

-

yellowgreen

-

#9acd32

-

-
+**Table 1** Color enums + +| Name | Hexadecimal Code | Color | +| -------------------- | -------- | ---------------------------------------- | +| aliceblue | \#f0f8ff | ![en-us_image_0000001173324803](figures/en-us_image_0000001173324803.png) | +| antiquewhite | \#faebd7 | ![en-us_image_0000001127285014](figures/en-us_image_0000001127285014.png) | +| aqua | \#00ffff | ![en-us_image_0000001127285050](figures/en-us_image_0000001127285050.png) | +| aquamarine | \#7fffd4 | ![en-us_image_0000001173324729](figures/en-us_image_0000001173324729.png) | +| azure | \#f0ffff | ![en-us_image_0000001127285040](figures/en-us_image_0000001127285040.png) | +| beige | \#f5f5dc | ![en-us_image_0000001173324773](figures/en-us_image_0000001173324773.png) | +| bisque | \#ffe4c4 | ![en-us_image_0000001173164895](figures/en-us_image_0000001173164895.png) | +| black | \#000000 | ![en-us_image_0000001173324735](figures/en-us_image_0000001173324735.png) | +| blanchedalmond | \#ffebcd | ![en-us_image_0000001173164889](figures/en-us_image_0000001173164889.png) | +| blue | \#0000ff | ![en-us_image_0000001127125194](figures/en-us_image_0000001127125194.png) | +| blueviolet | \#8a2be2 | ![en-us_image_0000001127285046](figures/en-us_image_0000001127285046.png) | +| brown | \#a52a2a | ![en-us_image_0000001173324833](figures/en-us_image_0000001173324833.png) | +| burlywood | \#deB887 | ![en-us_image_0000001127285026](figures/en-us_image_0000001127285026.png) | +| cadetblue | \#5f9ea0 | ![en-us_image_0000001127125210](figures/en-us_image_0000001127125210.png) | +| chartreuse | \#7fff00 | ![en-us_image_0000001173324811](figures/en-us_image_0000001173324811.png) | +| chocolate | \#d2691e | ![en-us_image_0000001127125256](figures/en-us_image_0000001127125256.png) | +| coral | \#ff7f50 | ![en-us_image_0000001173164877](figures/en-us_image_0000001173164877.png) | +| cornflowerblue | \#6495ed | ![en-us_image_0000001173324781](figures/en-us_image_0000001173324781.png) | +| cornsilk | \#fff8dc | ![en-us_image_0000001127285048](figures/en-us_image_0000001127285048.png) | +| crimson | \#dc143c | ![en-us_image_0000001127285066](figures/en-us_image_0000001127285066.png) | +| cyan | \#00ffff | ![en-us_image_0000001173324789](figures/en-us_image_0000001173324789.png) | +| darkblue | \#00008b | ![en-us_image_0000001173164841](figures/en-us_image_0000001173164841.png) | +| darkcyan | \#008b8b | ![en-us_image_0000001173324745](figures/en-us_image_0000001173324745.png) | +| darkgoldenrod | \#b8860b | ![en-us_image_0000001173324835](figures/en-us_image_0000001173324835.png) | +| darkgray | \#a9a9a9 | ![en-us_image_0000001127285028](figures/en-us_image_0000001127285028.png) | +| darkgreen | \#006400 | ![en-us_image_0000001127284990](figures/en-us_image_0000001127284990.png) | +| darkgrey | \#a9a9a9 | ![en-us_image_0000001127125174](figures/en-us_image_0000001127125174.png) | +| darkkhaki | \#bdb76b | ![en-us_image_0000001127285070](figures/en-us_image_0000001127285070.png) | +| darkmagenta | \#8b008b | ![en-us_image_0000001173164875](figures/en-us_image_0000001173164875.png) | +| darkolivegreen | \#556b2f | ![en-us_image_0000001173164835](figures/en-us_image_0000001173164835.png) | +| darkorange | \#ff8c00 | ![en-us_image_0000001127125178](figures/en-us_image_0000001127125178.png) | +| darkorchid | \#9932cc | ![en-us_image_0000001173324829](figures/en-us_image_0000001173324829.png) | +| darkred | \#8b0000 | ![en-us_image_0000001173164851](figures/en-us_image_0000001173164851.png) | +| darksalmon | \#e9967a | ![en-us_image_0000001127284998](figures/en-us_image_0000001127284998.png) | +| darkseagreen | \#8fbc8f | ![en-us_image_0000001173324755](figures/en-us_image_0000001173324755.png) | +| darkslateblue | \#483d8b | ![en-us_image_0000001127125246](figures/en-us_image_0000001127125246.png) | +| darkslategray | \#2f4f4f | ![en-us_image_0000001127125190](figures/en-us_image_0000001127125190.png) | +| darkslategrey | \#2f4f4f | ![en-us_image_0000001173324759](figures/en-us_image_0000001173324759.png) | +| darkturquoise | \#00ced1 | ![en-us_image_0000001127284980](figures/en-us_image_0000001127284980.png) | +| darkviolet | \#9400d3 | ![en-us_image_0000001127285058](figures/en-us_image_0000001127285058.png) | +| deeppink | \#ff1493 | ![en-us_image_0000001173324767](figures/en-us_image_0000001173324767.png) | +| deepskyblue | \#00bfff | ![en-us_image_0000001173164897](figures/en-us_image_0000001173164897.png) | +| dimgray | \#696969 | ![en-us_image_0000001127285022](figures/en-us_image_0000001127285022.png) | +| dimgrey | \#696969 | ![en-us_image_0000001173164911](figures/en-us_image_0000001173164911.png) | +| dodgerblue | \#1e90ff | ![en-us_image_0000001173164855](figures/en-us_image_0000001173164855.png) | +| firebrick | \#b22222 | ![en-us_image_0000001127125234](figures/en-us_image_0000001127125234.png) | +| floralwhite | \#fffaf0 | ![en-us_image_0000001173324771](figures/en-us_image_0000001173324771.png) | +| forestgreen | \#228b22 | ![en-us_image_0000001173324825](figures/en-us_image_0000001173324825.png) | +| fuchsia | \#ff00ff | ![en-us_image_0000001127285052](figures/en-us_image_0000001127285052.png) | +| gainsboro | \#dcdcdc | ![en-us_image_0000001173164901](figures/en-us_image_0000001173164901.png) | +| ghostwhite | \#f8f8ff | ![en-us_image_0000001127285012](figures/en-us_image_0000001127285012.png) | +| gold | \#ffd700 | ![en-us_image_0000001173324761](figures/en-us_image_0000001173324761.png) | +| goldenrod | \#daa520 | ![en-us_image_0000001173324817](figures/en-us_image_0000001173324817.png) | +| gray | \#808080 | ![en-us_image_0000001127125238](figures/en-us_image_0000001127125238.png) | +| green | \#008000 | ![en-us_image_0000001173164865](figures/en-us_image_0000001173164865.png) | +| greenyellow | \#adff2f | ![en-us_image_0000001127285000](figures/en-us_image_0000001127285000.png) | +| grey | \#808080 | ![en-us_image_0000001127285054](figures/en-us_image_0000001127285054.png) | +| honeydew | \#f0fff0 | ![en-us_image_0000001173324813](figures/en-us_image_0000001173324813.png) | +| hotpink | \#ff69b4 | ![en-us_image_0000001127285016](figures/en-us_image_0000001127285016.png) | +| indianred | \#cd5c5c | ![en-us_image_0000001173164849](figures/en-us_image_0000001173164849.png) | +| indigo | \#4b0082 | ![en-us_image_0000001173324821](figures/en-us_image_0000001173324821.png) | +| ivory | \#fffff0 | ![en-us_image_0000001173164887](figures/en-us_image_0000001173164887.png) | +| khaki | \#f0e68c | ![en-us_image_0000001173324801](figures/en-us_image_0000001173324801.png) | +| lavender | \#e6e6fa | ![en-us_image_0000001127125188](figures/en-us_image_0000001127125188.png) | +| lavenderblush | \#fff0f5 | ![en-us_image_0000001173324809](figures/en-us_image_0000001173324809.png) | +| lawngreen | \#7cfc00 | ![en-us_image_0000001127125224](figures/en-us_image_0000001127125224.png) | +| lemonchiffon | \#fffacd | ![en-us_image_0000001173164879](figures/en-us_image_0000001173164879.png) | +| lightblue | \#add8e6 | ![en-us_image_0000001127125180](figures/en-us_image_0000001127125180.png) | +| lightcoral | \#f08080 | ![en-us_image_0000001127125228](figures/en-us_image_0000001127125228.png) | +| lightcyan | \#e0ffff | ![en-us_image_0000001173324799](figures/en-us_image_0000001173324799.png) | +| lightgoldenrodyellow | \#fafad2 | ![en-us_image_0000001127125218](figures/en-us_image_0000001127125218.png) | +| lightgray | \#d3d3d3 | ![en-us_image_0000001127284974](figures/en-us_image_0000001127284974.png) | +| lightgreen | \#90ee90 | ![en-us_image_0000001173324805](figures/en-us_image_0000001173324805.png) | +| lightpink | \#ffb6c1 | ![en-us_image_0000001127285038](figures/en-us_image_0000001127285038.png) | +| lightsalmon | \#ffa07a | ![en-us_image_0000001173324795](figures/en-us_image_0000001173324795.png) | +| lightseagreen | \#20b2aa | ![en-us_image_0000001173324737](figures/en-us_image_0000001173324737.png) | +| lightskyblue | \#87cefa | ![en-us_image_0000001127285042](figures/en-us_image_0000001127285042.png) | +| lightslategray | \#778899 | ![en-us_image_0000001127125226](figures/en-us_image_0000001127125226.png) | +| lightslategrey | \#778899 | ![en-us_image_0000001127125222](figures/en-us_image_0000001127125222.png) | +| lightsteelblue | \#b0c4de | ![en-us_image_0000001127284976](figures/en-us_image_0000001127284976.png) | +| lightyellow | \#ffffe0 | ![en-us_image_0000001173324807](figures/en-us_image_0000001173324807.png) | +| lime | \#00ff00 | ![en-us_image_0000001127285020](figures/en-us_image_0000001127285020.png) | +| limegreen | \#32cd32 | ![en-us_image_0000001127125236](figures/en-us_image_0000001127125236.png) | +| linen | \#faf0e6 | ![en-us_image_0000001173324739](figures/en-us_image_0000001173324739.png) | +| magenta | \#ff00ff | ![en-us_image_0000001127285044](figures/en-us_image_0000001127285044.png) | +| maroon | \#800000 | ![en-us_image_0000001127285018](figures/en-us_image_0000001127285018.png) | +| mediumaquamarine | \#66cdaa | ![en-us_image_0000001173164899](figures/en-us_image_0000001173164899.png) | +| mediumblue | \#0000cd | ![en-us_image_0000001127284968](figures/en-us_image_0000001127284968.png) | +| mediumorchid | \#ba55d3 | ![en-us_image_0000001127125216](figures/en-us_image_0000001127125216.png) | +| mediumpurple | \#9370db | ![en-us_image_0000001173324779](figures/en-us_image_0000001173324779.png) | +| mediumseagreen | \#3cb371 | ![en-us_image_0000001127125230](figures/en-us_image_0000001127125230.png) | +| mediumslateblue | \#7b68ee | ![en-us_image_0000001173164921](figures/en-us_image_0000001173164921.png) | +| mediumspringgreen | \#00fa9a | ![en-us_image_0000001173324793](figures/en-us_image_0000001173324793.png) | +| mediumturquoise | \#48d1cc | ![en-us_image_0000001127125214](figures/en-us_image_0000001127125214.png) | +| mediumvioletred | \#c71585 | ![en-us_image_0000001173164893](figures/en-us_image_0000001173164893.png) | +| midnightblue | \#191970 | ![en-us_image_0000001127125260](figures/en-us_image_0000001127125260.png) | +| mintcream | \#f5fffa | ![en-us_image_0000001127285030](figures/en-us_image_0000001127285030.png) | +| mistyrose | \#ffe4e1 | ![en-us_image_0000001173324785](figures/en-us_image_0000001173324785.png) | +| moccasin | \#ffe4b5 | ![en-us_image_0000001127125232](figures/en-us_image_0000001127125232.png) | +| navajowhite | \#ffdead | ![en-us_image_0000001173164925](figures/en-us_image_0000001173164925.png) | +| navy | \#000080 | ![en-us_image_0000001127285032](figures/en-us_image_0000001127285032.png) | +| oldlace | \#fdf5e6 | ![en-us_image_0000001127125184](figures/en-us_image_0000001127125184.png) | +| olive | \#808000 | ![en-us_image_0000001127125244](figures/en-us_image_0000001127125244.png) | +| olivedrab | \#6b8e23 | ![en-us_image_0000001173324839](figures/en-us_image_0000001173324839.png) | +| orange | \#ffa500 | ![en-us_image_0000001173164885](figures/en-us_image_0000001173164885.png) | +| orangered | \#ff4500 | ![en-us_image_0000001127284996](figures/en-us_image_0000001127284996.png) | +| orchid | \#da70d6 | ![en-us_image_0000001127285056](figures/en-us_image_0000001127285056.png) | +| palegoldenrod | \#eee8aa | ![en-us_image_0000001127125262](figures/en-us_image_0000001127125262.png) | +| palegreen | \#98fb98 | ![en-us_image_0000001127285006](figures/en-us_image_0000001127285006.png) | +| paleturquoise | \#afeeee | ![en-us_image_0000001173324757](figures/en-us_image_0000001173324757.png) | +| palevioletred | \#db7093 | ![en-us_image_0000001173164905](figures/en-us_image_0000001173164905.png) | +| papayawhip | \#ffefd5 | ![en-us_image_0000001127125248](figures/en-us_image_0000001127125248.png) | +| peachpuff | \#ffdab9 | ![en-us_image_0000001173324769](figures/en-us_image_0000001173324769.png) | +| peru | \#cd853f | ![en-us_image_0000001173164843](figures/en-us_image_0000001173164843.png) | +| pink | \#ffc0cb | ![en-us_image_0000001127125242](figures/en-us_image_0000001127125242.png) | +| plum | \#dda0dd | ![en-us_image_0000001173324831](figures/en-us_image_0000001173324831.png) | +| powderblue | \#b0e0e6 | ![en-us_image_0000001127285010](figures/en-us_image_0000001127285010.png) | +| purple | \#800080 | ![en-us_image_0000001127285002](figures/en-us_image_0000001127285002.png) | +| rebeccapurple | \#663399 | ![en-us_image_0000001173164907](figures/en-us_image_0000001173164907.png) | +| red | \#ff0000 | ![en-us_image_0000001127125254](figures/en-us_image_0000001127125254.png) | +| rosybrown | \#bc8f8f | ![en-us_image_0000001173324775](figures/en-us_image_0000001173324775.png) | +| royalblue | \#4169e1 | ![en-us_image_0000001127284972](figures/en-us_image_0000001127284972.png) | +| saddlebrown | \#8b4513 | ![en-us_image_0000001127125250](figures/en-us_image_0000001127125250.png) | +| salmon | \#fa8072 | ![en-us_image_0000001127285064](figures/en-us_image_0000001127285064.png) | +| sandybrown | \#f4a460 | ![en-us_image_0000001173324777](figures/en-us_image_0000001173324777.png) | +| seagreen | \#2e8b57 | ![en-us_image_0000001173324733](figures/en-us_image_0000001173324733.png) | +| seashell | \#fff5ee | ![en-us_image_0000001127285062](figures/en-us_image_0000001127285062.png) | +| sienna | \#a0522d | ![en-us_image_0000001173164917](figures/en-us_image_0000001173164917.png) | +| silver | \#c0c0c0 | ![en-us_image_0000001173324743](figures/en-us_image_0000001173324743.png) | +| skyblue | \#87ceeb | ![en-us_image_0000001127284970](figures/en-us_image_0000001127284970.png) | +| slateblue | \#6a5acd | ![en-us_image_0000001173164915](figures/en-us_image_0000001173164915.png) | +| slategray | \#708090 | ![en-us_image_0000001173324815](figures/en-us_image_0000001173324815.png) | +| slategrey | \#708090 | ![en-us_image_0000001127284982](figures/en-us_image_0000001127284982.png) | +| snow | \#fffafa | ![en-us_image_0000001173324731](figures/en-us_image_0000001173324731.png) | +| springgreen | \#00ff7f | ![en-us_image_0000001127285060](figures/en-us_image_0000001127285060.png) | +| steelblue | \#4682b4 | ![en-us_image_0000001127125240](figures/en-us_image_0000001127125240.png) | +| tan | \#d2b48c | ![en-us_image_0000001173324747](figures/en-us_image_0000001173324747.png) | +| teal | \#008080 | ![en-us_image_0000001173324741](figures/en-us_image_0000001173324741.png) | +| thistle | \#d8Bfd8 | ![en-us_image_0000001173164913](figures/en-us_image_0000001173164913.png) | +| tomato | \#ff6347 | ![en-us_image_0000001173164909](figures/en-us_image_0000001173164909.png) | +| turquoise | \#40e0d0 | ![en-us_image_0000001173164837](figures/en-us_image_0000001173164837.png) | +| violet | \#ee82ee | ![en-us_image_0000001127125258](figures/en-us_image_0000001127125258.png) | +| wheat | \#f5deb3 | ![en-us_image_0000001127285068](figures/en-us_image_0000001127285068.png) | +| white | \#ffffff | ![en-us_image_0000001173324823](figures/en-us_image_0000001173324823.png) | +| whitesmoke | \#f5f5f5 | ![en-us_image_0000001127284992](figures/en-us_image_0000001127284992.png) | +| yellow | \#ffff00 | ![en-us_image_0000001173324837](figures/en-us_image_0000001173324837.png) | +| yellowgreen | \#9acd32 | ![en-us_image_0000001173164923](figures/en-us_image_0000001173164923.png) | diff --git a/en/application-dev/reference/arkui-js/js-components-basic-button.md b/en/application-dev/reference/arkui-js/js-components-basic-button.md index 771a5a55404f5bccfab8350837e74dc049bdc298..6e9378efe275d52ea6e28a4e51baa6170f5d6a7c 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-button.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-button.md @@ -1,340 +1,89 @@ -# button +# button -The **** component includes capsule, circle, text, arc, and download buttons. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Child Components +The **\ @@ -346,7 +95,7 @@ When the button type is **download**, the following methods are supported. ``` -``` +```css /* xxx.css */ .div-button { flex-direction: column; @@ -389,8 +138,8 @@ When the button type is **download**, the following methods are supported. } ``` -``` -// xxx.js +```js +// xxx.js export default { data: { count: 5, @@ -407,5 +156,4 @@ export default { } ``` -![](figures/1.png) - +![1](figures/1.png) diff --git a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md index 26518c022573079391bf9601f412ce12d0078615..de967be1f6e0ec184ce0d6ba553b0fe15a7ea5dd 100644 --- a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -1,7 +1,8 @@ # AnimatorProperty -> **NOTE**
+> **NOTE** +> > This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -18,27 +19,28 @@ When the universal attributes of a component change, you can create an **Animato - Curve enums - | Name | Description | + | Name | Description | | -------- | -------- | - | Linear | The animation speed keeps unchanged. | - | Ease | The animation starts at a low speed and then accelerates. It slows down before the animation ends. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used. | - | EaseIn | The animation starts at a low speed. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used. | - | EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used. | - | EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used. | - | FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0). | - | LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0). | - | FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0). | - | ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0). | - | Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0). | - | Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0). | - | Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0). | - | Friction | Damping curve. The cubic-bezier curve (0.2, 0.0, 0.2, 1.0) is used. | + | Linear | The animation speed keeps unchanged. | + | Ease | The animation starts at a low speed and then accelerates. It slows down before the animation ends. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used. | + | EaseIn | The animation starts at a low speed. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used. | + | EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used. | + | EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used. | + | FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0). | + | LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0). | + | FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0). | + | ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0). | + | Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0). | + | Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0). | + | Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0). | + | Friction | Damping curve. The cubic-bezier curve (0.2, 0.0, 0.2, 1.0) is used. | ## Example -``` +```ts +// xxx.ets @Entry @Component struct AttrAnimationExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md index 45c82eb1f973f1bc808fcb642943282b1610abb1..3eeec830107e6896a2bb07ba4cdb0a31028ecae6 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md @@ -1,7 +1,8 @@ # Blank -> **NOTE**
+> **NOTE** +> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -15,7 +16,7 @@ None ## Child Components -None +Not supported ## APIs @@ -23,16 +24,16 @@ None Blank(min?: Length) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | min | Length | No | 0 | Minimum size of the **<Blank>** component in the container along the main axis. | + | min | Length | No | 0 | Minimum size of the **<Blank>** component in the container along the main axis. | ## Attributes - | Name | Type | Default Value | Description | +| Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| color | Color | 0x00000000 | Color to fill the blank. | +| color | Color | 0x00000000 | Color to fill the blank. | > **NOTE**
> Universal attribute methods are not supported. @@ -40,8 +41,9 @@ Blank(min?: Length) ## Example - -``` + +```ts +// xxx.ets @Entry @Component struct BlankExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md index 509b8dc54ee19a841106c67f07db98de16a04f03..dd19c78cbb68ac35799b90ffe8d9dc67070aa7e8 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md @@ -1,18 +1,18 @@ # Checkbox -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - - The **\** component is used to enable or disable an option. +> **NOTE** +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## Required Permissions None ## Child Components -None +Not supported ## APIs @@ -30,7 +30,7 @@ Checkbox( name?: string, group?: string ) | Name | Type| Default Value| Description| | ------------- | ------- | ------ | -------- | -| select | bool | false | Whether the check box is selected.| +| select | boolean | false | Whether the check box is selected.| | selectedColor | Color | - | Color of the check box when it is selected.| ## Events @@ -41,7 +41,8 @@ Checkbox( name?: string, group?: string ) ## Example -``` +```ts +// xxx.ets @Entry @Component struct CheckboxExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index c84392d085212ca08859ce0d641276f41a4a5e59..38be1957f15aab6f3308d2f27cc65f0713534293 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -1,17 +1,18 @@ # CheckboxGroup -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - The **\** component is used to select or deselect all check boxes in a group. +> **NOTE** +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## Required Permissions None ## Child Components -None +Not supported ## APIs @@ -27,19 +28,19 @@ Creates a check box group so that you can select or deselect all check boxes in ## Attributes -| Name| Type| Default Value| Description| +| Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| selectAll | bool | false | Whether to select all.| -| selectedColor | Color | - | Color of the selected check box.| +| selectAll | boolean | false | Whether to select all.| +| selectedColor | Color | - | Color of the selected check box.| ## Events -| Name| Description| +| Name| Description| | -------- | -------- | -| onChange (callback: (names: Array<string>, status: SelectStatus) => void ) |Triggered when the selection status of the check box group or any check box wherein changes.
- **names**: names of all selected check boxes in the group.
- **status**: selection status.| +| onChange (callback: (names: Array<string>, status: SelectStatus) => void ) |Triggered when the selection status of the check box group or any check box wherein changes.
- **names**: names of all selected check boxes in the group.
- **status**: selection status.| - SelectStatus enums - | Name | Description| + | Name | Description| | ----- | -------------------- | | All | All check boxes in the group are selected.| | Part | Some check boxes in the group are selected.| @@ -48,7 +49,8 @@ Creates a check box group so that you can select or deselect all check boxes in ## Example -``` +```ts +// xxx.ets @Entry @Component struct CheckboxExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md index ccd812f6941077dd9d5fff1f5cb214a87c430f03..336b0ce5a027f197255e8ee122d76beb2b03d852 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md @@ -1,7 +1,8 @@ # Divider -> **NOTE**
+> **NOTE** +> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -15,7 +16,7 @@ None ## Child Components -None +Not supported ## APIs @@ -41,7 +42,8 @@ Universal events are not supported. ## Example -``` +```ts +// xxx.ets @Entry @Component struct DividerExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index 2843fa89b82d978bc58a696b6196a9ffdd37f71b..88231686024e14774633850d6707b8c5c3e77080 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -149,8 +149,6 @@ struct ImageExample1 { @Entry @Component struct ImageExample2 { - @State width: number = 100 - @State height: number = 100 build() { Column({ space: 10 }) { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md index 8b3e291ae48eff833e349ea3bc025441b53f7067..435ab557cbe82515bf73b9a5a613c08f14dafae3 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md @@ -1,12 +1,10 @@ # ImageAnimator - -> **NOTE**
-> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - The **\** component enables images to be played frame by frame. The list of images to be played can be configured, and the duration of each image can be configured. +> **NOTE** +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Required Permissions @@ -27,7 +25,7 @@ ImageAnimator() | Name | Type | Default Value | Mandatory | Description | | -------- | -------- | -------- | -------- | -------- | -| images | Array<{
src:string,
width?:Length,
height?:Length,
top?:Length,
left?:Length,
duration?:number
}> | [] | Yes | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. The detailed description is as follows:
**src**: image path. The image format can be SVG, PNG, or JPG.
**width**: image width.
**height**: image height.
**top**: vertical coordinate of the image relative to the upper left corner of the component.
**left**: horizontal coordinate of the image relative to the upper left corner of the component.
**duration**: playback duration of the image, in ms. | +| images | Array<{
src:string,
width?:Length,
height?:Length,
top?:Length,
left?:Length,
duration?:number
}> | [] | Yes | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. The detailed description is as follows:
**src**: image path. The image format can be SVG, PNG, or JPG.
**width**: image width.
**height**: image height.
**top**: vertical coordinate of the image relative to the upper left corner of the component.
**left**: horizontal coordinate of the image relative to the upper left corner of the component.
**duration**: playback duration of the image, in ms. | | state | AnimationStatus | AnimationStatus.Initial | No | Playback status of the animation. The default status is **Initial**. | | duration | number | 1000 | No | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in images, the setting of this attribute is invalid. | | reverse | boolean | false | No | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one. | @@ -36,6 +34,15 @@ ImageAnimator() | fillMode | FillMode | FillMode.Forwards | No | Status before and after the animation starts. For details about the options, see **FillMode**. | | iterations | number | 1 | No | By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. | +- ImageFrameInfo + | Name| Type| Default Value| Mandatory| Description| + | -------- | -------- | -------- | -------- | -------- | + | src | string \| [Resource](.../ui/ts-types.md#resource-type)9+| "" | Yes| Image path. The image format can be .svg, .png, or .jpg.| + | width | [Length](.../ui/ts-types.md#length-type)| 0 | No| Image width.| + | height | [Length](.../ui/ts-types.md#length-type)| 0 | No| Image height.| + | top | [Length](.../ui/ts-types.md#length-type)| 0 | No| Vertical coordinate of the image relative to the upper left corner of the component.| + | left | [Length](.../ui/ts-types.md#length-type)| 0 | No| Horizontal coordinate of the image relative to the upper left corner of the component.| + | duration | number | 0 | No| Playback duration of each image frame, in milliseconds.| - AnimationStatus enums | Name | Description | | -------- | -------- | @@ -54,7 +61,7 @@ ImageAnimator() ## Events | Name | Description | -| -------- | -------- | +| -------- | -------- | | onStart() => void | Triggered when the animation starts to play. | | onPause() => void | Triggered when the animation playback is paused. | | onRepeat() => void | Triggered when the animation playback is repeated. | @@ -65,7 +72,8 @@ ImageAnimator() ## Example -``` +```ts +// xxx.ets @Entry @Component struct ImageAnimatorExample { @@ -95,7 +103,7 @@ struct ImageAnimatorExample { left: 0 }, { - src: '/comment/bg3.jpg', + src: $r('app.media.bg3'), duration: 500, width: 325, height: 200, @@ -103,7 +111,7 @@ struct ImageAnimatorExample { left: 0 }, { - src: '/comment/bg4.jpg', + src: $rawfile('bg4.jpg'), duration: 500, width: 325, height: 200, @@ -127,6 +135,7 @@ struct ImageAnimatorExample { console.info('Cancel') }) .onFinish(() => { // Triggered after the frame animation playback is complete. + this.state = AnimationStatus.Stopped console.info('Finish') }) Row() { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index b4d89bd97a63514d77f168827d73e1f800de6c1d..aa4168ce4bda28ed25064f6cedc45875c1aa2440 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -1,11 +1,11 @@ # Navigation - -> **NOTE**
-> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component typically functions as the root container of a page and displays the page title, toolbar, and menu based on the attribute settings. -The **<Navigation>** component typically functions as the root container of a page and displays the page title, toolbar, and menu based on the attribute settings. +> **NOTE** +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. ## Required Permissions @@ -30,7 +30,7 @@ Creates a component that can automatically display the navigation bar, title, an | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | | title | string \| [CustomBuilder](../../ui/ts-types.md) | - | Page title. | -| subtitle | string | - | Subtitle of the page. | +| subTitle | string | - | Subtitle of the page. | | menus | Array<NavigationMenuItem> \| [CustomBuilder](../../ui/ts-types.md) | - | Menu in the upper right corner of the page. | | titleMode | NavigationTitleMode | NavigationTitleMode.Free | Display mode of the page title bar. | | toolBar | {
items:[
Object
] }
\| [CustomBuilder](../../ui/ts-types.md) | - | Content of the toolbar.
**items**: all items on the toolbar. | @@ -60,6 +60,7 @@ Creates a component that can automatically display the navigation bar, title, an | Full | The mode is fixed at full mode (main title and subtitle). | > **NOTE** + > > Currently, only the scrollable component **<List>** is supported. @@ -73,8 +74,8 @@ Creates a component that can automatically display the navigation bar, title, an ## Example -``` -// Example 01 +```ts +// xxx.ets @Entry @Component struct NavigationExample { @@ -161,9 +162,8 @@ struct NavigationExample { ![en-us_image_0000001256978359](figures/en-us_image_0000001256978359.gif) - -``` -// Example 02 +```ts +// xxx.ets @Entry @Component struct ToolbarBuilderExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md b/en/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md index bcd71854410102552d8c5b3ee5aa00db33bd8fec..66478d5a194c9d16390d509d0cba95e52486d756 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md @@ -1,9 +1,11 @@ # PatternLock -> **NOTE**
+The **\** component allows users to use a pattern password for authentication. It enters the input state once being touched, and exits the input state and sends the entered password to the application once the finger leaves the screen. + +> **NOTE** +> > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component allows users to use a pattern password for authentication. It enters the input state once being touched, and exits the input state and sends the entered password to the application once the finger leaves the screen. ## Required Permissions @@ -11,7 +13,7 @@ None ## Child Components -None +Not supported ## APIs @@ -62,7 +64,8 @@ Resets the component status. ## Example -```typescript +```ts +// xxx.ets @Entry @Component struct PatternLockExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md index 7042bd3ba82f54b30556ed24626cde3a1aea0d73..15cbc7066707a773f3cbc0ecd5c970eb46d1b249 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-plugincomponent.md @@ -1,13 +1,11 @@ # PluginComponent +**\** allows the UI provided by an external application to be displayed in the application. > **NOTE** -> - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > -> - The APIs of this module are system APIs and cannot be called by third-party applications. - - -**<PluginComponent>** allows the UI provided by an external application to be displayed in the application. +> - The APIs provided by this module are system APIs. ## Required Permissions @@ -17,7 +15,7 @@ None ## Child Components -None +Not supported ## APIs @@ -31,24 +29,24 @@ Creates a **PluginComponent** to display the UI provided by an external applicat | -------- | -------- | -------- | -------- | -------- | | value | {
template: PluginComponentTemplate,
data: KVObject
} | Yes | - | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.
**data**: data passed to the **PluginComponent** provider. | -- PluginComponentTemplate parameters - | Name | Type | Description | +- PluginComponentTemplate + | Name | Type | Description | | -------- | -------- | -------- | - | source | string | Component template name. | - | ability | string | Name of the provider ability. | + | source | string | Component template name. | + | ability | string | Name of the provider ability. | ## Events -| Name | Description | +| Name | Description | | -------- | -------- | -| onComplete(callback: () => void) | Triggered when the component loading is complete. | -| onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information. | +| onComplete(callback: () => void) | Triggered when the component loading is complete. | +| onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information. | ## PluginComponentManager -Provides APIs for the **PluginComponent**. You can use these APIs to request components and data and send component templates and data. +Provides APIs for the **PluginComponent** user to request the component and data and for the **PluginComponent** provider to push component templates and data. ## Modules to Import @@ -59,70 +57,67 @@ import pluginComponentManager from '@ohos.plugincomponent' ``` -## Required Permissions - -None - - ## push push(param: PushParameters, callback: AsyncCallback<void>): void -Used by the component provider to send the component and data to the component consumer. +Used by the component provider to push a component and data to the component user. - Parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | param | PushParameters | Yes | Information about the component consumer. For details, see description of PushParameters. | + | param | PushParameters | Yes | Information about the component user. For details, see **PushParameters**. | | callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result. | -- Description of PushParameters +- PushParameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | want | Want | Yes | Ability information of the component consumer. | + | want | Want | Yes | Ability information of the component user. | | name | string | Yes | Component name. | | data | KVObject | No | Component data value. | | extraData | KVObject | No | Additional data value. | -- Example
- For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers). +- Example + + See [PluginComponent Provider](#plugincomponent-provider)。 ## request request(param: RequestParameters, callback: AsyncCallback<RequestCallbackParameters>): void -Used by the component consumer to request the component from the component provider. +Used by the component user to request a component from the component provider. - Parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | param | RequestParameters | Yes | Information about the component request. For details, see  description of RequestParameters. | + | param | RequestParameters | Yes | Information about the component request. For details, see  **RequestParameters**. | | callback | AsyncCallback - For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers). +- Example + + See [PluginComponent User](#plugincomponent-user). ## on @@ -134,39 +129,39 @@ Listens for events of the request type and returns the requested data, or listen - Parameters | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | eventType | string | Yes | Type of the event to listen for. The options are **"push"** and **"request"**.
**"push"**: The component provider pushes data to the component consumer.
**"request"**: The component consumer proactively requests data from the component provider. | + | eventType | string | Yes | Type of the event to listen for. The options are **"push"** and **"request"**.
**"push"**: The component provider pushes data to the component user.
**"request"**: The component user proactively requests data from the component provider. | | callback | OnPushEventCallback \| OnRequestEventCallback | Yes | Callback used to return the result. For details, see description of callback. | -- Description of callback +- callback | Name | Type | Description | | -------- | -------- | -------- | | OnRequestEventCallback | (source: Want,
name: string,
data: KVObject ) =>RequestEventResult | Callback for the data request event.
**source**: ability information of the component requester.
**name**: name of the requested component.
**data**: additional data.
Return value: request data and result. | | OnPushEventCallback | (source: Want,
template: PluginComponentTemplate,
data: KVObject,
extraData: KVObject
) => void | Callback used to receive the data pushed by the component provider.
**source**: ability information of the component provider.
**template**: component template.
**data**: component update data.
**extraData**: additional data. | -- Description of RequestEventResult +- RequestEventResult | Name | Type | Description | | -------- | -------- | -------- | | template | string | Component name. | | data | KVObject | Component data. | | extraData | KVObject | Additional data. | -- Example
- For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers). +- Example + See [PluginComponent Tools](#plugincomponent-tools). ## Example -### Using the PluginComponent +### PluginComponent User -``` -import plugin from "../../test/plugin_component.js" -import plugincomponent from '@ohos.plugincomponent' +```ts +//PluginUserExample.ets +import plugin from "plugin_component.js" @Entry @Component -struct PluginComponentExample { +struct PluginUserExample { @StorageLink("plugincount") plugincount: Object[] = [ { source: 'plugincomponent1', ability: 'com.example.plugin' }, { source: 'plugintemplate', ability: 'com.example.myapplication' }, @@ -177,32 +172,23 @@ struct PluginComponentExample { Text('Hello World') .fontSize(50) .fontWeight(FontWeight.Bold) - Button('Push') - .fontSize(50) - .width(400) - .height(100) - .onClick(() => { - plugin.Push() - console.log("Button('Push')") - }) - .margin({ top: 20 }) - Button('Request1') - .fontSize(50) + Button('Register Request Listener') + .fontSize(30) .width(400) .height(100) - .margin({ top: 20 }) - .onClick(() => { - plugin.Request1() - console.log("Button('Request1')") + .margin({top:20}) + .onClick(()=>{ + plugin.onListener() + console.log("Button('Register Request Listener')") }) - Button('Request2') + Button('Request') .fontSize(50) .width(400) .height(100) .margin({ top: 20 }) .onClick(() => { - plugin.Request2() - console.log("Button('Request2')") + plugin.Request() + console.log("Button('Request')") }) ForEach(this.plugincount, item => { PluginComponent({ @@ -219,15 +205,58 @@ struct PluginComponentExample { } .width('100%') .height('100%') + } } ``` +### PluginComponent Provider -### APIs Called by Component Consumers +```ts +//PluginProviderExample.ets +import plugin from "plugin_component.js" +@Entry +@Component +struct PluginProviderExample { + @State message: string = 'no click!' + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Button('Register Push Listener') + .fontSize(30) + .width(400) + .height(100) + .margin({top:20}) + .onClick(()=>{ + plugin.onListener() + console.log("Button('Register Push Listener')") + }) + Button('Push') + .fontSize(30) + .width(400) + .height(100) + .margin({top:20}) + .onClick(()=>{ + plugin.Push() + this.message = "Button('Push')" + console.log("Button('Push')") + }) + Text(this.message) + .height(150) + .fontSize(30) + .padding(5) + .margin(5) + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) + } +} ``` -import pluginComponentManager from '@ohos.plugincomponent' + +### PluginComponent Tools + + +```js +//plugin_component.js +import pluginComponentManager from '@ohos.pluginComponent' function onPushListener(source, template, data, extraData) { console.log("onPushListener template.source=" + template.source) @@ -244,14 +273,23 @@ function onPushListener(source, template, data, extraData) { console.log("onPushListener extraData=" + JSON.stringify(extraData)) } +function onRequestListener(source, name, data) +{ + console.log("onRequestListener name=" + name); + console.log("onRequestListener data=" + JSON.stringify(data)); + return {template:"plugintemplate", data:data}; +} + export default { //register listener onListener() { pluginComponentManager.on("push", onPushListener) + pluginComponentManager.on("request", onRequestListener) }, - Request() { - //The component consumer proactively sends data. - pluginComponentManager.request({ + Push() { + // The component provider pushes data. + pluginComponentManager.push( + { want: { bundleName: "com.example.myapplication", abilityName: "com.example.myapplication.MainAbility", @@ -261,43 +299,19 @@ export default { "key_1": "plugin component test", "key_2": 34234 }, - jsonPath: "assets/js", + extraData: { + "extra_str": "this is push event" + }, + jsonPath: "", }, (err, data) => { - console.log("request_callback1: componentTemplate.ability=" + data.componentTemplate.ability) - console.log("request_callback1: componentTemplate.source=" + data.componentTemplate.source) - var jsonObject = JSON.parse(data.componentTemplate.source) - console.log("request_callback1:source json object" + jsonObject) - var jsonArry = jsonObject.ExternalComponent - for (var i in jsonArry) { - console.log(jsonArry[i]) - } - console.log("request_callback1:source json string" + JSON.stringify(jsonObject)) - console.log("request_callback1: data=" + JSON.stringify(data.data)) - console.log("request_callback1: extraData=" + JSON.stringify(data.extraData)) + console.log("push_callback: push ok!"); } ) - } -} - -// Example of the component provider using the API -import pluginComponentManager from '@ohos.plugincomponent' - -function onRequestListener(source, name, data) { - console.log("onRequestListener name=" + name) - console.log("onRequestListener data=" + JSON.stringify(data)) - return { template: "plugintemplate", data: data } -} - -export default { - //register listener - onListener() { - pluginComponentManager.on("request", onRequestListener) }, - Push() { - // The component provider proactively sends data. - pluginComponentManager.push( - { + Request() { + // The component user proactively sends data. + pluginComponentManager.request({ want: { bundleName: "com.example.myapplication", abilityName: "com.example.myapplication.MainAbility", @@ -307,17 +321,22 @@ export default { "key_1": "plugin component test", "key_2": 34234 }, - extraData: { - "extra_str": "this is push event" - }, - jsonPath: "assets/js", + jsonPath: "", }, (err, data) => { - console.log("push_callback1: componentTemplate.ability=" + data.componentTemplate.ability) - console.log("push_callback1: componentTemplate.source=" + data.componentTemplate.source) - console.log("push ok!") + console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) + var jsonObject = JSON.parse(data.componentTemplate.source) + console.log("request_callback:source json object" + jsonObject) + var jsonArry = jsonObject.ExternalComponent + for (var i in jsonArry) { + console.log(jsonArry[i]) + } + console.log("request_callback:source json string" + JSON.stringify(jsonObject)) + console.log("request_callback: data=" + JSON.stringify(data.data)) + console.log("request_callback: extraData=" + JSON.stringify(data.extraData)) } ) - }, + } } ``` diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md index 070100aedd7cd1c5ef1c0fa8d6dd842c3e9eb79e..7ea05b944a8783a03ce702eac0c904cb5d35760c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -1,9 +1,10 @@ # Search -> **NOTE**
+The **\** component provides an input area for users to search. +> **NOTE** +> > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component provides an input area for users to search. ## Required Permissions @@ -11,7 +12,7 @@ None ## Child Components -None +Not supported ## APIs @@ -41,21 +42,21 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll | Name | Description | | -------- | -------- | -| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or tap the search button on a soft keyboard.
-**value**: current text input. | -| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.
-**value**: current text input. | -| onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard.
-**value**: text copied. | -| onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard.
-**value**: text cut. | -| onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.
-**value**: text pasted. | +| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or tap the search button on a soft keyboard.
- **value**: current text input. | +| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.
- **value**: current text input. | +| onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard.
- **value**: text copied. | +| onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard.
- **value**: text cut. | +| onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.
- **value**: text pasted. | ## SearchController Defines the controller of the **\** component. -#### Objects to Import +### Objects to Import ``` controller: SearchController = new SearchController() ``` -#### caretPosition +### caretPosition caretPosition(value: number): void diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md index d995c8213360200087233f9d636d7bdb6d1a2410..0a0365a9d3ff3672f346425bab7317a8a83e2694 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md @@ -1,11 +1,12 @@ # TextPicker -> **NOTE**
-> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component allows users to select text from a list of options. -The **<TextPicker>** component allows users to select text from a list of options. +> **NOTE** +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. ## Required Permissions @@ -15,27 +16,28 @@ None ## Child Components -None +Not supported ## APIs -TextPicker(value: {range: string[], selected?: number}) +TextPicker(value: {range: string[] | Resource, value?: string, selected?: number}) Creates a text picker based on the selection range specified by **range**. -- Parameter +- Parameters | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | range | string[] | Yes | - | Data selection range of the picker. | - | selected | number | No | - | Index value of the selected item in the array. By default, the first element is selected. | + | range | string[]\| [Resource](../../ui/ts-types.md) | Yes | - | Data selection range of the picker. | + | value | string | No | - | Search text. | + | selected | number | No | Index of the first item | Index of the selected item in the array. | ## Attributes | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| defaultPickerItemHeight | Length | - | Default height of a Picker content item element. | +| defaultPickerItemHeight | Length | - | Default height of an item in the picker. | ## Events @@ -48,7 +50,8 @@ Creates a text picker based on the selection range specified by **range**. ## Example -``` +```ts +// xxx.ets @Entry @Component struct TextPickerExample { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md index f399b16210ca59f3409217b6136443515a3be6d1..6ccd555886c1bf5b46164cd313608998454fadd3 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md @@ -1,7 +1,9 @@ # SwipeGesture +**\** is used to implement a swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher. -> **NOTE**
+> **NOTE** +> > This gesture is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. @@ -33,13 +35,13 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num | Name | Description | | -------- | -------- | -| onAction(callback:(event?: GestureEvent) => void) | Callback invoked when a swipe gesture is recognized. | +| onAction(callback:(event?: GestureEvent) => void) | Invoked when a swipe gesture is recognized. | - GestureEvent attributes related to the swipe gesture | Name | Type | Description | | -------- | -------- | -------- | - | angle | number | Angle of the swipe gesture.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Angle calculation method: After the swipe gesture is identified, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction. Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1). The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. | + | angle | number | Angle of the swipe gesture.
**NOTE**
Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction. Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1). The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. | | speed | number | Speed of the swipe gesture. | ![en-us_image_0000001231374559](figures/en-us_image_0000001231374661.png) diff --git a/en/application-dev/reference/arkui-ts/ts-container-grid.md b/en/application-dev/reference/arkui-ts/ts-container-grid.md index fd33781664b0457ede59618260c7125043324de6..7e5c475facfb0d077d63bfee93eed0dd759de10a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/en/application-dev/reference/arkui-ts/ts-container-grid.md @@ -1,13 +1,12 @@ # Grid +The **\** component is a two-dimensional layout. The component is divided into rows and columns to form cells. You can specify the cell where an item is located and combine different grids to form various layouts. -> **NOTE**
+> **NOTE** +> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -The **<Grid>** component is a two-dimensional layout. The component is divided into rows and columns to form cells. You can specify the cell where an item is located and combine different grids to form various layouts. - - ## Required Permissions None @@ -15,7 +14,7 @@ None ## Child Components -This component contains the child component [](ts-container-griditem.md). +This component contains the child component [\](ts-container-griditem.md). ## APIs @@ -32,31 +31,24 @@ Grid() | columnsGap | Length | 0 | Spacing between columns. | | rowsGap | Length | 0 | Spacing between rows. | | editMode8+ | boolean | false | Whether to enter editing mode. In editing mode, you can drag the **<[GridItem](ts-container-griditem.md)>** in the **<Gird>** component. | -| layoutDirection8+ | [LayoutDirection](ts-appendix-enums.md#layoutdirection-enums) | LayoutDirection.Row | Main axis direction of the layout. The options are as follows:- **LayoutDirection.Row**: Horizontal layout, where the child components are arranged in the same direction as the main axis runs along the rows.- **LayoutDirection.Column**: Vertical layout, where the child components are arranged in the same direction as the main axis runs down the columns. | +| layoutDirection8+ | number | 0 | Main axis direction of the layout. The options are as follows:
- **0**: Horizontal layout, where the child components are arranged in the same direction as the main axis runs along the rows.
- **1**: Vertical layout, where the child components are arranged in the same direction as the main axis runs down the columns. | | maxCount8+ | number | 1 | Maximum number of rows that can be displayed. | | minCount8+ | number | 1 | Minimum number of rows that can be displayed. | | cellLength8+ | number | 0 | Fixed height per row. | | multiSelectable8+ | boolean | false | Whether to enable mouse frame selection.
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is disabled. | -| edgeEffection8+ | EdgeEffect | EdgeEffect.Spring | Edge effect. For details, see **EdgeEffect**. | - -- EdgeEffect enums - - | Name | Description | - | ------ | ------------------------------------------------------------ | - | Spring | Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded. | - | None | No effect after the scrollbar is moved to the edge. | +| supportAnimation8+ | boolean | false | Whether the grid layout supports animation. | ## Events -| Name | Description | +| Name | Description | | -------- | -------- | -| onScrollIndex(first: number) => void | Triggered when the start item of the grid changes. | +| onScrollIndex(first: number) => void | Triggered when the start item of the grid changes. | ## Example - -``` +```ts +// xxx.ets @Entry @Component struct GridExample { diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index ca85c43cf47556315915f6947fdd62a1d136bf24..5d11634e3bae94e58ac0589451c9076c7c356ecc 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -1,11 +1,12 @@ # List -> **NOTE**
+> **NOTE** +> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -The **List** component provides a list container that presents a series of list items arranged in a column with the same width. It supports presentation of the same type of data in a multiple and coherent row style, for example, images or text. +The **\** component provides a list container that presents a series of list items arranged in columns with the same width. It supports presentation of the same type of data, for example, images or text, in a multiple and coherent row style. ## Required Permissions @@ -15,12 +16,12 @@ None ## Child Components -This component contains the child component [](ts-container-listitem.md). +This component contains the child component [\](ts-container-listitem.md). ## APIs -List(value:{space?: number | string, initialIndex?: number, scroller?: Scroller}) +List(value:{space?: number, initialIndex?: number}) - Parameters | Name | Type | Mandatory | Default Value | Description | @@ -34,18 +35,28 @@ List(value:{space?: number | string, initialIndex?: number, scroller?: Scroller} | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | | listDirection | [Axis](ts-appendix-enums.md#axis-enums) | Vertical | Direction in which the list items are arranged. For details, see **Axis** enums. | -| divider | {
strokeWidth: Length,
color?:Color,
startMargin?: Length,
endMargin?: Length
} | - | Style of the divider for the list items. By default, there is no divider.
**strokeWidth**: stroke width of the divider.
**color**: color of the divider.
**startMargin**: distance between the divider and the start of the list.
**endMargin**: distance between the divider and the end of the list. | +| divider | {
strokeWidth: Length,
color?:Color,
startMargin?: Length,
endMargin?: Length
} | - | Style of the divider for the list items. By default, there is no divider.
**strokeWidth**: stroke width of the divider.
**color**: color of the divider.
**startMargin**: distance between the divider and the start of the list.
**endMargin**: distance between the divider and the end of the list. | | editMode | boolean | false | Whether the **<List>** component is in editable mode. | | edgeEffect | EdgeEffect | EdgeEffect.Spring | Sliding effect. For details, see EdgeEffect enums. | -| chainAnimation | boolean | false | Whether to display chained animations on this list when it slides or its top and bottom are dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed. | -| multiSelectable8+ | boolean | false | Whether to enable mouse frame selection.
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled. | -| restoreId8+ | number | - | Migration ID of the component. During application migration, the status of the component is migrated to the component with the same migration ID on the peer end.
For a **List** component, the status includes the item serial number displayed at the start position. | +| chainAnimation | boolean | false | Whether to display chained animations on this list when it slides or its top and bottom are dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed. | +| multiSelectable8+ | boolean | false | Whether to enable mouse frame selection.
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled. | +| restoreId8+ | number | - | Migration ID of the component. During application migration, the status of the component is migrated to the component with the same migration ID on the peer end.
For a **<\List>** component, the status includes the item serial number displayed at the start position. | +| lanes9+ | number \|
{
minLength: Length,
maxLength: Length
} | 1 | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
- If the value type is number, the column width is determined based on the specified number and the cross-axis width of the **\** component.
- If the value type is {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.| +| alignListItem9+ | ListItemAlign | ListItemAlign.Center | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.| - EdgeEffect enums | Name | Description | | -------- | -------- | - | Spring | Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded. | - | None | No effect after the scroll bar is moved to the edge. | + | Spring | Similar to the physical dynamic effect of a spring. After scrolling to the edge, the user can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After the user releases their hand, the knob is rebounded. | + | None | No effect after the scrollbar is moved to the edge. | + +- ListItemAlign enums + + | Name | Description | + | ------ | -------------------------------------- | + | Start | The list items are packed toward the start edge of the **\** component along the cross axis.| + | Center | The list items are centered in the **\** component along the cross axis.| + | End | The list items are packed toward the end edge of the **\** component in the cross axis.| ## Events @@ -55,26 +66,28 @@ List(value:{space?: number | string, initialIndex?: number, scroller?: Scroller} | onItemDelete(index: number) => boolean | Triggered when a list item is deleted. | | onScrollIndex(firstIndex: number, lastIndex: number) => void | Triggered when the start position and end position of the current list are changed. | -> **NOTE**
+> **NOTE** +> > To enable the editable mode for a list, the following conditions must be met: -> +> > - **editMode** is set to **true**. -> -> - The list is bound to the **onItemDelete** event and the event returns **true** during event callback. -> +> +> - The list is bound to the **onItemDelete** event, and the event returns **true** through a callback. +> > - The **editable** attribute of **ListItem** is set to **true**. -> +> > To enable dragging for a list item, the following conditions must be met: -> +> > - **editMode** is set to **true**. -> -> - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback. +> +> - The list item is bound to the **onDragStart** event, and the event returns a floating UI through a callback. ## Example -``` +```ts +// xxx.ets @Entry @Component struct ListExample { @@ -121,3 +134,48 @@ struct ListExample { ``` ![en-us_image_0000001256978357](figures/en-us_image_0000001256978357.gif) + +```ts +// xxx.ets +@Entry +@Component +struct ListLanesExample { + @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"] + @State alignListItem: ListItemAlign = ListItemAlign.Start + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%') + .height(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .border({ width: 2, color: Color.Green }) + }, item => item) + } + .height(300) + .width("90%") + .editMode(true) + .border({ width: 3, color: Color.Red }) + .lanes({ minLength: 40, maxLength: 60 }) + .alignListItem(this.alignListItem) + + Button("Change alignListItem: "+ this.alignListItem).onClick(() => { + if (this.alignListItem == ListItemAlign.Start) { + this.alignListItem = ListItemAlign.Center + } else if (this.alignListItem == ListItemAlign.Center) { + this.alignListItem = ListItemAlign.End + } else { + this.alignListItem = ListItemAlign.Start + } + }) + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) + } +} +``` diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index c322905170ed581bacb72fded4d580940fd7c664..dc55a6741f7bd0bc72bb12d1238c5c1896845372 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -1,6 +1,7 @@ # Video -> **NOTE**
+> **NOTE** +> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. The **\