diff --git a/CODEOWNERS b/CODEOWNERS index f395d69420381a4e61268211787acd0cff417ec5..52fd5a5404d2809b3e021c09d932c9f4a9cc050f 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -85,6 +85,7 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin +zh-cn/device-dev/subsystems/subsys-security-huks-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23 @@ -348,4 +349,6 @@ zh-cn/application-dev/napi/napi-guidelines.md @RayShih zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen -zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease \ No newline at end of file +zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease +zh-cn/application-dev/website.md @zengyawen +zh-cn/application-dev/faqs/ @zengyawen \ No newline at end of file diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability/stage-call.md index aaa9a9918345c52015969245c3bbba3efbb81048..6b5823e76db2c95190111a55b9d2ef43ddd2d946 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -19,7 +19,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r |API|Description| |:------|:------| |startAbilityByCall(want: Want): Promise\|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| -|on(method: string, callback: CaleeCallBack): void|Callback invoked when the callee registers a method.| +|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee registers a method.| |off(method: string): void|Callback invoked when the callee deregisters a method.| |call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee.| |callWithResult(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| @@ -28,7 +28,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r ## How to Develop > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. For details about the complete project code, see [Samples](#samples). +> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. ### Creating a Callee For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener. 1. Configure the ability startup mode. diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index dde1feb495e9827ab1f0fd1fad903f71acb9cbb3..cfde2b66f2a3094355d6166bcaa4fb17856fbfaf 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -17,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 @@ -35,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 @@ -85,7 +85,11 @@ The following example shows how to implement a distributed data object synchroni ```js import distributedObject from '@ohos.data.distributedDataObject'; ``` -2. Request the permission.
Add the required permission in the **config.json** file. The sample code is as follows: + +2. Request the permission. + + Add the required permission in the **config.json** file. The sample code is as follows: + ``` { "module": { @@ -97,10 +101,11 @@ The following example shows how to implement a distributed data object synchroni } } ``` - This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows: - ```js + This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows: + + ``` import featureAbility from '@ohos.ability.featureAbility'; - + function grantPermission() { console.info('grantPermission'); let context = featureAbility.getContext(); @@ -108,11 +113,13 @@ The following example shows how to implement a distributed data object synchroni console.info(`result.requestCode=${result.requestCode}`) }) - console.info('end grantPermission'); + console.info('end grantPermission'); } grantPermission(); ``` - + + + 3. Obtain a distributed data object instance. The sample code is as follows: @@ -130,7 +137,7 @@ The following example shows how to implement a distributed data object synchroni ```js // Local object var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true, - parent:{mother:"jack mom",father:"jack Dad"},list:[{mother:"jack mom"}, {father:"jack Dad"}]}); + parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]}); local_object.setSessionId(sessionId); // Remote object @@ -140,8 +147,10 @@ The following example shows how to implement a distributed data object synchroni // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. ``` -5. Observe the data changes of the distributed data object.
You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes. +5. Observe the data changes of the distributed data object. + You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes. + The sample code is as follows: ```js @@ -152,26 +161,32 @@ The following example shows how to implement a distributed data object synchroni changeData.forEach(element => { console.info("changed !" + element + " " + local_object[element]); }); - } + } } - + // To refresh the page in changeCallback, correctly bind (this) to the changeCallback. 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 local_object.name = "jack"; local_object.age = 19; local_object.isVis = false; - local_object.parent = {mother:"jack mom",father:"jack Dad"}; + local_object.parent = {mother:"jack mom", father:"jack Dad"}; local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}]; ``` - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
- > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example: + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. + + Example: + ```js // Supported modification. local_object.parent = {mother:"mom", father:"dad"}; @@ -179,13 +194,18 @@ The following example shows how to implement a distributed data object synchroni local_object.parent.mother = "mom"; ``` -7. Access the distributed data object.
Obtain the distributed data object attribute, which is the latest data on the network. - +7. Access the distributed data object. + + Obtain the distributed data object attribute, which is the latest data on the network. + The sample code is as follows: ```js console.info("name " + local_object["name"]); ``` -8. Unsubscribe from data changes.
You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. + +8. Unsubscribe from data changes. + + You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. The sample code is as follows: ```js @@ -194,6 +214,7 @@ The following example shows how to implement a distributed data object synchroni // Unregister all data change callbacks. local_object.off("change"); ``` + 9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. The sample code is as follows: ```js @@ -207,58 +228,62 @@ 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 unregisters 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 + ```js // Unregister the specified status change callback. local_object.off("status", this.statusCallback); // Unregister all status change callbacks. local_object.off("status"); - ``` + ``` + 12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. The sample code is as follows: ```js local_object.setSessionId(""); ``` -## Development Example - -The following example is provided for you to better understand the development of distributed data objects: - -- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad) - - -When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network. diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index c5608c6eabd526c38a87bd3907fba89fb1a11629..dd1594215a10d1c93c9825444253484ed8956e05 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -6,22 +6,20 @@ 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.| -| 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. | +| API | Description | +| ------------------------------------------------------------ | ----------------------------------------------- | +| createKVManager(config:KVManagerConfig,callback:AsyncCallback<KVManager>):void
createKVManager(config:KVManagerConfig):Promise<KVManager> | Creates a **KVManager** object for database management.| +| getKVStore<TextendsKVStore>(storeId:string,options:Options,callback:AsyncCallback<T>):void
getKVStore<TextendsKVStore>(storeId:string,options:Options):Promise<T> | Obtains a KV store with the specified **Options** and **storeId**.| +| 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. | +| delete(key:string,callback:AsyncCallback<void>):void
delete(key:string):Promise<void> | Deletes data. | +| get(key:string,callback:AsyncCallback<Uint8Array\|string\|boolean\|number>):void
get(key:string):Promise<Uint8Array\|string\|boolean\|number> | Queries 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. | +| sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. | @@ -36,11 +34,14 @@ The following uses a single KV store as an example to describe the development p ``` 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. + (2) Create a **KvManager** instance. + The sample code is as follows: - ```js + + ``` let kvManager; try { const kvManagerConfig = { @@ -62,9 +63,12 @@ The following uses a single KV store as an example to describe the development p console.log("An unexpected error occurred. Error:" + e); } ``` - + + 3. Create and obtain a single KV store. + (1) Declare the ID of the single KV store to create. + (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: @@ -92,8 +96,9 @@ 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**
- > 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. + > **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.
The following is the sample code for subscribing to the data changes of a single KV store: @@ -104,7 +109,9 @@ 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. The following is the sample code for writing key-value pairs of the string type into the single KV store: @@ -126,7 +133,9 @@ 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. The following is the sample code for querying data of the string type from the single KV store: @@ -152,7 +161,11 @@ The following uses a single KV store as an example to describe the development p 7. Synchronize data to other devices.
Select the devices in the same network and the synchronization mode to synchronize data. - The following is the sample code for data synchronization in a single KV store. **deviceIds** can be obtained by deviceManager by calling **getTrustedDeviceListSync()**, and **1000** indicates that the maximum delay time is 1000 ms. + > **NOTE** + > + > The APIs of the `deviceManager` module are system interfaces. + + The following is the sample code for synchronizing data in a single KV store: ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; @@ -161,7 +174,7 @@ The following uses a single KV store as an example to describe the development p deviceManager.createDeviceManager("bundleName", (err, value) => { if (!err) { devManager = value; - // Obtain deviceIds. + // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync(). let deviceIds = []; if (devManager != null) { var devices = devManager.getTrustedDeviceListSync(); @@ -170,6 +183,7 @@ The following uses a single KV store as an example to describe the development p } } try{ + // 1000 indicates that the maximum delay is 1000 ms. kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); }catch (e) { console.log("An unexpected error occurred. Error:" + e); @@ -177,7 +191,3 @@ 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-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 7f93b1ca5684d4268ca7fe46e35442a776a3b201..f6c7395339d66cb1c79bf71d424c15072f77f1b6 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -7,7 +7,7 @@ A relational database (RDB) store allows you to operate local data with or witho ## Available APIs -For details about RDB APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). +Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For details about the APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). ### Creating or Deleting an RDB Store @@ -15,51 +15,48 @@ The table below describes the APIs available for creating and deleting an RDB st **Table 1** APIs for creating and deleting an RDB store -| API| Description| -| -------- | -------- | -|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.| +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| 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 call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: version of the RDB store.| +| 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**: name of the RDB store to delete.| ### Managing Data in an RDB Store The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. -- **Inserting data** +- **Inserting Data** The RDB provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. - **Table 2** APIs for inserting data + **Table 2** API for inserting data - | Class| API| Description| - | -------- | -------- | -------- | - | 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.| + | Class | API | Description | + | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | insert(table:string,values:ValuesBucket):Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| -- **Updating data** +- **Updating Data** Call the **update()** method to pass new data and specify the update conditions by using **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. - **Table 3** APIs for updating data + **Table 3** API for updating data - | Class| API| Description| - | -------- | -------- | -------- | - | 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.| + | Class | API | Description | + | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | update(values:ValuesBucket,predicates:RdbPredicates):Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data.
Return value: number of rows updated. | -- **Deleting data** +- **Deleting Data** Call the **delete()** method to delete data meeting the conditions specified by **RdbPredicates**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. - **Table 4** APIs for deleting data + **Table 4** API for deleting data - | Class| API| Description| - | -------- | -------- | -------- | - | 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.| + | Class | API | Description | + | -------- | ------------------------------------------------------ | ------------------------------------------------------------ | + | 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.
Return value: number of rows updated. | -- **Querying data** + + +- **Querying Data** You can query data in an RDB store in either of the following ways: @@ -68,78 +65,48 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 5** APIs for querying data - | Class| API| Description| - | -------- | -------- | -------- | - | 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.| - | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>): void |Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to query.
- **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 | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to query.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | Class | API | Description | + | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | query(predicates:RdbPredicates,columns?:Array<string>):Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql:string,bindArgs?:Array<ValueType>):Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicates** that specifies the query condition.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| ### Using Predicates The RDB provides **RdbPredicates** for you to set database operation conditions. +The following lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). + **Table 6** APIs for using RDB store predicates -| Class| API| Description| -| -------- | -------- | -------- | -| RdbPredicates |inDevices(devices: Array\): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| -| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| -| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| -| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| -| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| -| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNull(field: string): RdbPredicates | Sets an **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets an **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets ta **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets an **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets an **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | distinct(): RdbPredicates | Sets an **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| -| RdbPredicates | limitAs(value: number): RdbPredicates | Sets an **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| -| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| -| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets an **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| -| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets an **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| -| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| Class | API | Description | +| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| +| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the OR condition.| +| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the AND condition.| +| RdbPredicates | contains(field:string,value:string):RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| + ### Using the Result Set -A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. +A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. + +For details about how to use result set APIs, see [Result Set](../reference/apis/js-apis-data-resultset.md). > **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly. **Table 7** APIs for using the result set -| Class| API| Description| -| -------- | -------- | -------- | -| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| -| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| -| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| -| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| -| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| -| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| -| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set.| -| ResultSet | goToLastRow(): boolean | Moves to the last row of the result set.| -| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| -| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| -| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| -| ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| -| ResultSet | close(): void | Closes the result set.| +| Class | API | Description | +| --------- | ---------------------------------------------------- | ------------------------------------------ | +| ResultSet | goToFirstRow():boolean | Moves to the first row of the result set. | +| ResultSet | getString(columnIndex:number):string | Obtains the value in the form of a string based on the specified column and current row. | +| ResultSet | getBlob(columnIndex:number):Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| +| ResultSet | getDouble(columnIndex:number):number | Obtains the value in the form of double based on the specified column and current row. | +| ResultSet | getLong(columnIndex:number):number | Obtains the value in the form of a long integer based on the specified column and current row. | +| ResultSet | close():void | Closes the result set. | @@ -149,78 +116,73 @@ A result set can be regarded as a row of data in the queried results. It allows **Setting Distributed Tables** -**Table 8** APIs for setting distributed tables +**Table 8** API for setting distributed tables -| Class| API| Description| -| -------- | -------- | -------- | -| 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.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** You can obtain the distributed table name for a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device. -**Table 9** APIs for obtaining the distributed table name of a remote device +**Table 9** API for obtaining the distributed table name of a remote device -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is 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.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** -**Table 10** APIs for synchronizing data between devices +**Table 10** API for synchronizing data between devices -| Class| API| Description| -| -------- | -------- | -------- | -| 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.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** **Table 11** API for registering an observer -| 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.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** **Table 12** API for unregistering an observer -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\>): void;| Unregisters the observer of the specified type for the RDB store. This 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.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** 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 +**Table 13** API 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.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| 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 +**Table 14** API 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.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | restore(srcName:string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| **Transaction** Table 15 Transaction APIs -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore |beginTransaction():void| Starts the transaction before executing SQL statements.| -| RdbStore |commit():void| Commits the executed SQL statements.| -| RdbStore |rollBack():void| Rolls back the SQL statements that have been executed.| +| Class | API | Description | +| -------- | ----------------------- | --------------------------------- | +| RdbStore | beginTransaction():void | Starts the transaction before executing SQL statements.| +| RdbStore | commit():void | Commits the executed SQL statements. | +| RdbStore | rollBack():void | Rolls back the SQL statements that have been executed. | ## How to Develop @@ -238,7 +200,7 @@ Table 15 Transaction APIs 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",} + 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.') @@ -255,7 +217,7 @@ Table 15 Transaction APIs ```js var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} + const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8} let insertPromise = rdbStore.insert("test", valueBucket) ``` @@ -424,3 +386,4 @@ Table 15 Transaction APIs console.info('Restore failed, err: ' + err) }) ``` + diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index d65d0abfc4d4649f7f1847abdbe6fb0a832e194e..faf977c7b42644a03066947e45996a936529f8cc 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -39,28 +39,28 @@ 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.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.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.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.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 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; @@ -68,7 +68,7 @@ function setCallBack(audioPlayer) { console.info('audio seek success, and seek time is ' + seekDoneTime); 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') { @@ -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,11 +119,11 @@ 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.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. @@ -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.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.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. @@ -223,7 +223,7 @@ 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. @@ -247,7 +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. } } ``` diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 6b5bbc8aa3d671c4cf0b01316db441d33c0f189f..edee55c375b0cc31b8f6305ed7fb24397bad12b0 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -19,6 +19,7 @@ - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) + - [@ohos.application.WindowExtensionAbility](js-apis-application-WindowExtensionAbility.md) - application/[AbilityContext](js-apis-ability-context.md) - application/[ApplicationContext](js-apis-application-applicationContext.md) - application/[AbilityStageContext](js-apis-abilitystagecontext.md) @@ -68,18 +69,25 @@ - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) + - [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) + - [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md) - [@ohos.zlib](js-apis-zlib.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) + - bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md) - bundle/[CustomizeData](js-apis-bundle-CustomizeData.md) + - bundle/[DispatchInfo](js-apis-dispatchInfo.md) - bundle/[ElementName](js-apis-bundle-ElementName.md) - bundle/[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) - bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md) + - bundle/[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md) - bundle/[Metadata](js-apis-bundle-Metadata.md) - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - + - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) + - bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) + - bundle/[ShortcutInfo](js-apis-bundle-ShortcutInfo.md) - UI Page - [@ohos.animator](js-apis-animator.md) @@ -90,6 +98,7 @@ - Graphics + - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - [@ohos.display ](js-apis-display.md) - [@ohos.effectKit](js-apis-effectKit.md) - [@ohos.screen](js-apis-screen.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md new file mode 100644 index 0000000000000000000000000000000000000000..3691d636ac769e8bfad9099f92554a2476925d40 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -0,0 +1,307 @@ +# innerBundleManager + +The **innerBundleManager** module manages internal bundles. + +> **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 + +``` +import innerBundleManager from '@ohos.bundle.innerBundleManager'; +``` + +## System Capability + +SystemCapability.BundleManager.BundleFramework + +## Required Permissions + +| Permission | Permission Level | Description | +| ------------------------------------------ | ------------ | ---------------------------- | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications. | +| ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant | Permission to listen for application changes.| + +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). + +## innerBundleManager.getLauncherAbilityInfos + +getLauncherAbilityInfos(bundleName: string, userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; + +Obtains the launcher ability information based on a given bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | + + + +## innerBundleManager.getLauncherAbilityInfos + +getLauncherAbilityInfos(bundleName: string, userId: number) : Promise<Array<LauncherAbilityInfo>> + +Obtains the launcher ability information based on a given bundle name. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ----------------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise\> | Promise used to return an array of the launcher ability information.| + +## innerBundleManager.on + +on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback, callback: AsyncCallback<string>) : void; + +Registers a callback to receive bundle status changes. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | --------------------- | ---- | ---------------------------------------------------- | +| type | "BundleStatusChange" | Yes | Event type. | +| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register. | +| callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| + +## innerBundleManager.on + +on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback): Promise<string> + +Registers a callback to receive bundle status changes. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------- | ---- | ------------------ | +| type | "BundleStatusChange" | Yes | Event type. | +| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register.| + +**Return value** + +| Type | Description | +| --------------- | ----------------------------------- | +| Promise\ | Promise used to return a successful result or error information.| + +## innerBundleManager.off + +off(type:"BundleStatusChange", callback: AsyncCallback<string>) : void; + +Deregisters the callback that receives bundle status changes. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------------------- | +| type | "BundleStatusChange" | Yes | Event type. | +| callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| + +## innerBundleManager.off + +off(type:"BundleStatusChange"): Promise<string> + +Deregisters the callback that receives bundle status changes. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | -------------------- | ---- | ---------------- | +| type | "BundleStatusChange" | Yes | Event type.| + +**Return value** + +| Type | Description | +| --------------- | ----------------------------------- | +| Promise\ | Promise used to return a successful result or error information.| + +## innerBundleManager.getAllLauncherAbilityInfos + +getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; + +Obtains the information about all launcher abilities. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | + +## innerBundleManager.getAllLauncherAbilityInfos + +getAllLauncherAbilityInfos(userId: number) : Promise<Array<LauncherAbilityInfo>> + +Obtains the information about all launcher abilities. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------------------- | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise\> | Promise used to return an array of the launcher ability information.| + +## innerBundleManager.getShortcutInfos + +getShortcutInfos(bundleName :string, callback: AsyncCallback<Array<ShortcutInfo>>) : void; + +Obtains the shortcut information based on a given bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| callback | AsyncCallback\> | Yes | Callback used to return an array of the shortcut information.| + +## innerBundleManager.getShortcutInfos + +getShortcutInfos(bundleName : string) : Promise<Array<ShortcutInfo>> + +Obtains the shortcut information based on a given bundle name. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------------------ | +| bundleName | string | Yes | Bundle name of an application.| + +**Return value** + +| Type | Description | +| -------------------------------------------------------- | ----------------------------- | +| Promise\> | Promise used to return an array of the shortcut information.| diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md new file mode 100644 index 0000000000000000000000000000000000000000..f321aca70ed972845f73ca702501e574aeafe5e0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -0,0 +1,139 @@ +# distributedBundle + +The **distributedBundle** module manages distributed bundles. + +> **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 + +``` +import distributedBundle from '@ohos.distributedBundle'; +``` + +## System Capability + +SystemCapability.BundleManager.DistributedBundleFramework + +## Required Permissions + +| Permission | Permission Level | Description | +| ------------------------------------------ | ------------ | ------------------ | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications.| + +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void; + +Obtains information about the remote ability that matches the given element name. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**. | +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Yes | Callback used to return the remote ability information.| + + + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo> + +Obtains information about the remote ability that matches the given element name. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | -------------------------------------------- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Promise used to return the remote ability information.| + +## distributedBundle.getRemoteAbilityInfos + +getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void; + +Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | +| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return an array of the remote ability information.| + + + +## distributedBundle.getRemoteAbilityInfos + +getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>> + +Obtains information about remote abilities that match the given element names. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------------- | ---- | ----------------------- | +| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\> | Promise used to return an array of the remote ability information.| diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 94d93df6aa2f25bfce6b2094cfe06a88429df346..e487baedfd496a9ac0a6e90332aa99f3323a4fc2 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -39,11 +39,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -81,12 +81,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -119,11 +119,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -155,10 +155,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------- | ---- | --------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory| Description | +| ---------- | ---------- | ---- | ------------------------------------------------------------ | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -195,10 +195,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | --------------------------------- | ---- | --------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -229,11 +229,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | --------------------------------- | ---- | --------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -268,7 +268,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- | --------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | **Return value** @@ -309,11 +309,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -346,12 +346,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -847,10 +847,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | --------------------------------------- | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -889,11 +889,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------------------- | ---- | --------------------------------------- | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -926,10 +926,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------------------- | ---- | --------------------------------------- | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -959,7 +959,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| **Return value** | Type | Description | @@ -994,7 +994,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.| **Example** @@ -1474,7 +1474,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ------------------------------------- | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. For details on the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -1518,12 +1518,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. For details on the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -1559,11 +1559,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. For details on the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index ce415ad942510c481755380bdd90adb7eb1c75ae..c432f719593a2aa3f32db509b339b2cc783ea5b4 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -4,8 +4,7 @@ The **Context** module provides context for abilities or applications. It allows > **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 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 can be used only in the FA model. ## Usage @@ -30,9 +29,9 @@ If this API is called for the first time, a root directory will be created. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the local root directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the local root directory.| **Example** @@ -58,8 +57,8 @@ If this API is called for the first time, a root directory will be created. **Return value** -| Type | Description | -| ---------------- | ---------------------- | +| Type | Description | +| ---------------- | ----------- | | Promise\ | Promise used to return the local root directory.| **Example** @@ -84,11 +83,11 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ------------------------------------- | -| permission | string | Yes | Name of the permission to verify. | -| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------------- | ---- | -------------------- | +| permission | string | Yes | Name of the permission to verify. | +| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -113,10 +112,10 @@ Verifies whether the current PID and UID have the given permission. This API use **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------- | ---- | ------------------------------------- | -| permission | string | Yes | Name of the permission to verify. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------- | ---- | -------------------- | +| permission | string | Yes | Name of the permission to verify. | +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -136,15 +135,15 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ---------------- | -| permission | string | Yes | Name of the permission to verify.| -| options | [PermissionOptions](#permissionoptions) | No | Permission options. | +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------------- | ---- | -------- | +| permission | string | Yes | Name of the permission to verify.| +| options | [PermissionOptions](#permissionoptions) | No | Permission options. | **Return value** -| Type | Description | -| ---------------- | ----------------------------------------------------------- | +| Type | Description | +| ---------------- | ---------------------------------- | | Promise\ | Promise used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -171,11 +170,11 @@ Requests certain permissions from the system. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | -| permissions | Array\ | Yes | Permissions to request. This parameter cannot be **null**. | -| requestCode | number | Yes | Request code to be passed to **PermissionRequestResult**.| -| resultCallback | AsyncCallback<[PermissionRequestResult](#permissionrequestresult)> | Yes | Permission request result. | +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ----------------------------------- | +| permissions | Array\ | Yes | Permissions to request. This parameter cannot be **null**. | +| requestCode | number | Yes | Request code to be passed to **PermissionRequestResult**.| +| resultCallback | AsyncCallback<[PermissionRequestResult](#permissionrequestresult)> | Yes | Permission request result. | **Example** @@ -207,9 +206,9 @@ Obtains information about the current application. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the application information.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the application information.| **Example** @@ -231,8 +230,8 @@ Obtains information about the current application. This API uses a promise to re **Return value** -| Type | Description | -| ------------------------- | ------------------ | +| Type | Description | +| ------------------------- | --------- | | Promise\ | Promise used to return the application information.| **Example** @@ -258,9 +257,9 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -282,8 +281,8 @@ Obtains the bundle name of this ability. This API uses a promise to return the r **Return value** -| Type | Description | -| ---------------- | ------------------------- | +| Type | Description | +| ---------------- | ---------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -307,9 +306,9 @@ Obtains the display orientation of this ability. This API uses an asynchronous c **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| **Example** @@ -329,9 +328,9 @@ Obtains the display orientation of this ability. This API uses a promise to retu **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Promise used to return the display orientation.| +| Type | Description | +| ---------------------------------------- | --------- | +| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation.| **Example** @@ -348,16 +347,16 @@ context.getDisplayOrientation().then((data) => { setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback\): void -Obtains the display orientation for this ability. This API uses an asynchronous callback to return the result. +Sets the display orientation for this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-bundle.md#displayorientation) | Yes | Display orientation to set.| -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ------------ | +| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.| +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation. | **Example** @@ -375,16 +374,16 @@ context.setDisplayOrientation(orientation, (err) => { setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise\; -Obtains the display orientation for this ability. This API uses a promise to return the result. +Sets the display orientation for this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-bundle.md#displayorientation) | Yes | Display orientation to set.| -| Promise\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Promise used to return the display orientation.| +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | +| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | +| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation. | **Example** @@ -403,16 +402,16 @@ context.setDisplayOrientation(orientation).then((data) => { setShowOnLockScreen(show: boolean, callback: AsyncCallback\): void -Sets whether to show this feature at the top of the lock screen each time the lock screen is displayed so that the feature remains activated. This API uses an asynchronous callback to return the result. +Sets whether to show this feature at the top of the lock screen so that the feature remains activated. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | ---------------------------------------- | +| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -429,21 +428,21 @@ context.setShowOnLockScreen(show, (err) => { setShowOnLockScreen(show: boolean): Promise\; -Sets whether to show this feature at the top of the lock screen each time the lock screen is displayed so that the feature remains activated. This API uses a promise to return the result. +Sets whether to show this feature at the top of the lock screen so that the feature remains activated. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| +| Name | Type | Mandatory | Description | +| ---- | ------- | ---- | ---------------------------------------- | +| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\| Promise used to return the result.| +| Type | Description | +| -------------- | --------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -467,10 +466,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | --------------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -493,15 +492,15 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | --------------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\| Promise used to return the result.| +| Type | Description | +| -------------- | --------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -528,9 +527,9 @@ Obtains information about the current process, including the PID and process nam **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process information.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the process information.| **Example** @@ -552,8 +551,8 @@ Obtains information about the current process, including the PID and process nam **Return value** -| Type | Description | -| --------------------- | -------------- | +| Type | Description | +| --------------------- | ------- | | Promise\ | Promise used to return the process information.| **Example** @@ -581,9 +580,9 @@ This API is available only to Page abilities. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| **Example** @@ -607,8 +606,8 @@ This API is available only to Page abilities. **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | +| Type | Description | +| --------------------- | ------------------------------------ | | Promise\ | Promise used to return the **ohos.bundle.ElementName** object.| **Example** @@ -632,9 +631,9 @@ Obtains the name of the current process. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the process name.| **Example** @@ -656,8 +655,8 @@ Obtains the name of the current process. This API uses a promise to return the r **Return value** -| Type | Description | -| ---------------- | -------------------- | +| Type | Description | +| ---------------- | ---------- | | Promise\ | Promise used to return the process name.| **Example** @@ -683,9 +682,9 @@ Obtains the bundle name of the calling ability. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -707,8 +706,8 @@ Obtains the bundle name of the calling ability. This API uses a promise to retur **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | -------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -732,9 +731,9 @@ Obtains the cache directory of the application in the internal storage. This API **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the cache directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | --------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the cache directory.| **Example** @@ -760,8 +759,8 @@ Obtains the cache directory of the application in the internal storage. This API **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | --------------- | | Promise\ | Promise used to return the cache directory.| **Example** @@ -785,9 +784,9 @@ Obtains the file directory of the application in the internal storage. This API **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the file directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the file directory.| **Example** @@ -813,8 +812,8 @@ Obtains the file directory of the application in the internal storage. This API **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ------------------- | | Promise\ | Promise used to return the file directory.| **Example** @@ -840,9 +839,9 @@ If the distributed file path does not exist, the system will create one and retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| **Example** @@ -870,8 +869,8 @@ If the distributed file path does not exist, the system will create one and retu **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ----------------------------------- | | Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a new path will be created.| **Example** @@ -894,9 +893,9 @@ Obtains the application type. This API uses an asynchronous callback to return t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the application type.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the application type.| **Example** @@ -922,8 +921,8 @@ Obtains the application type. This API uses a promise to return the result. **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ------------------ | | Promise\ | Promise used to return the application type.| **Example** @@ -946,9 +945,9 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| **Example** @@ -974,8 +973,8 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | ------------------ | | Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| **Example** @@ -998,9 +997,9 @@ Obtains the version information of this application. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| **Example** @@ -1026,8 +1025,8 @@ Obtains the version information of this application. This API uses a promise to **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | --------- | | Promise\<[AppVersionInfo](#appversioninfo)> | Promise used to return the version information.| **Example** @@ -1050,9 +1049,9 @@ Obtains information about this ability. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** @@ -1078,8 +1077,8 @@ Obtains information about this ability. This API uses a promise to return the re **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | ------------------ | | Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise used to return the ability information.| **Example** @@ -1102,9 +1101,9 @@ Obtains the context of the application. **Return value** -| Type | Description | -| --------- |------ | -| Context | Application context.| +| Type | Description | +| ------- | ---------- | +| Context | Application context.| **Example** @@ -1117,15 +1116,15 @@ var context = featureAbility.getContext().getApplicationContext(); isUpdatingConfigurations(callback: AsyncCallback\): void; -Checks whether the configuration of this ability is being changed. This API uses an asynchronous callback to return the result. +Checks whether the configuration of this ability is being updated. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Returns **true** if the configuration of the capability is being changed; returns **false** otherwise.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ----------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the configuration of the capability is being updated; returns **false** otherwise.| **Example** @@ -1145,15 +1144,15 @@ context.isUpdatingConfigurations((err, data) => { isUpdatingConfigurations(): Promise\; -Checks whether the configuration of this ability is being changed. This API uses a promise to return the result. +Checks whether the configuration of this ability is being updated. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| --------------- | ------------------------- | -|Promise\ | Returns **true** if the configuration of the capability is being changed; returns **false** otherwise.| +| Type | Description | +| ----------------- | ----------------------------- | +| Promise\ | Returns **true** if the configuration of the capability is being updated; returns **false** otherwise.| **Example** @@ -1175,9 +1174,9 @@ Notifies the system of the time required to draw this page function. This API us **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | ----------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1203,9 +1202,9 @@ Notifies the system of the time required to draw this page function. This API us **Return value** -| Type | Description | -| --------------- | ------------------------- | -|Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | --------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -1222,27 +1221,27 @@ context.printDrawnCompleted().then((data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Readable/Writable| Type | Mandatory| Description | -| ---- | -------- | ------ | ---- | ------ | -| pid | Read-only | number | No | Process ID.| -| uid | Read-only | number | No | User ID.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ---- | ---- | ------ | ---- | ----- | +| pid | Read-only | number | No | Process ID.| +| uid | Read-only | number | No | User ID.| ## PermissionRequestResult7+ **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------- | ---- | ------------------ | -| requestCode | Read-only | number | Yes | Request code passed.| -| permissions | Read-only | Array\ | Yes | Permissions requested. | -| authResults | Read-only | Array\ | Yes | Permission request result. | +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | -------------- | ---- | ---------- | +| requestCode | Read-only | number | Yes | Request code passed.| +| permissions | Read-only | Array\ | Yes | Permissions requested. | +| authResults | Read-only | Array\ | Yes | Permission request result. | ## AppVersionInfo7+ **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type| Readable | Writable | Description| -| ------ | ------ | ------| ------ | ------ | -| appName | string | Yes | No | Module name. | -| versionCode | number | Yes | No | Module description. | -| versionName | string | Yes | No | Module description ID. | +| Name | Type | Readable | Writable | Description | +| ----------- | ------ | ---- | ---- | ------- | +| appName | string | Yes | No | Module name. | +| versionCode | number | Yes | No | Module description.| +| versionName | string | Yes | No | Module description ID.| diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index e2333a523a918e229c6a35c4e341df9383bfb26a..3b5d0bba1bb5954d3365d97cde619f5931c0f7a3 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -2,7 +2,7 @@ The **AbilityContext** module, inherited from **Context**, implements the context for abilities. -This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a pop-up window. +This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box. > **NOTE** > @@ -40,13 +40,11 @@ Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -71,13 +69,11 @@ Starts an ability with start options specified. This API uses an asynchronous ca **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| @@ -106,13 +102,11 @@ Starts an ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -153,7 +147,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want |[Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| @@ -181,7 +175,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want |[Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| @@ -214,7 +208,7 @@ Starts an ability. This API uses a promise to return the result when the ability | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| @@ -239,7 +233,7 @@ Starts an ability. This API uses a promise to return the result when the ability ## AbilityContext.startAbilityForResultWithAccount -startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback): void; +startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. @@ -253,8 +247,8 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -289,8 +283,8 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -312,7 +306,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca ``` - ## AbilityContext.startAbilityForResultWithAccount +## AbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; @@ -328,8 +322,8 @@ Starts an ability with start options specified. This API uses a promise to retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -358,7 +352,271 @@ Starts an ability with start options specified. This API uses a promise to retur console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); }) ``` +## AbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.startServiceExtensionAbility(want, (err) => { + console.log('---------- startServiceExtensionAbility fail, err: -----------', err); + }); + ``` + +## AbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want): Promise\; + +Starts a new Service Extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.startServiceExtensionAbility(want) + .then((data) => { + console.log('---------- startServiceExtensionAbility success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startServiceExtensionAbility fail, err: -----------', err); + }) + ``` +## AbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startServiceExtensionAbilityWithAccount(want,accountId, (err) => { + console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); + }); + ``` + +## AbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startServiceExtensionAbilityWithAccount(want,accountId) + .then((data) => { + console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); + }) + ``` +## AbilityContext.stopServiceExtensionAbility +stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.stopServiceExtensionAbility(want, (err) => { + console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); + }); + ``` + +## AbilityContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want): Promise\; + +Stops a Service Extension ability in the same application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.stopServiceExtensionAbility(want) + .then((data) => { + console.log('---------- stopServiceExtensionAbility success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); + }) + ``` + +## AbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.stopServiceExtensionAbilityWithAccount(want,accountId, (err) => { + console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); + }); + ``` + +## AbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.stopServiceExtensionAbilityWithAccount(want,accountId) + .then((data) => { + console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); + }) + ``` ## AbilityContext.terminateSelf @@ -412,7 +670,7 @@ Terminates this ability. This API uses a promise to return the result. terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses an asynchronous callback to return the information to the caller of **startAbilityForResult**. +Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -426,11 +684,17 @@ Terminates this ability. This API uses an asynchronous callback to return the in **Example** ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }, (error) => { + var want = { + "bundleName": "com.extreme.myapplication", + "abilityName": "SecondAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + this.context.terminateSelfWithResult(abilityResult, (error) => { console.log("terminateSelfWithResult is called = " + error.code) } ); @@ -441,7 +705,7 @@ Terminates this ability. This API uses an asynchronous callback to return the in terminateSelfWithResult(parameter: AbilityResult): Promise<void>; -Terminates this ability. This API uses a promise to return information to the caller of **startAbilityForResult**. +Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -460,11 +724,17 @@ Terminates this ability. This API uses a promise to return information to the ca **Example** ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }).then((result) => { + var want = { + "bundleName": "com.extreme.myapplication", + "abilityName": "SecondAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + this.context.terminateSelfWithResult(abilityResult).then((result) => { console.log("terminateSelfWithResult") } ) @@ -484,8 +754,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Remote object instance.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Parameters for the connection.| **Return value** @@ -515,7 +785,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability. +Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -527,8 +797,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Parameters for the connection.| **Return value** @@ -626,7 +896,7 @@ Obtains the caller interface of the specified ability, and if the specified abil | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, it indicates the local device.| **Return value** @@ -671,8 +941,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -706,8 +976,8 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -745,8 +1015,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| **Example** @@ -774,7 +1044,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; -Requests permissions from the user by displaying a pop-up window. This API uses an asynchronous callback to return the result. +Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -783,7 +1053,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the permission request result.| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result.| **Example** @@ -800,7 +1070,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; -Requests permissions from the user by displaying a pop-up window. This API uses a promise to return the result. +Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -814,7 +1084,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses | Type| Description| | -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the permission request result.| +| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| **Example** @@ -1006,7 +1276,7 @@ Checks whether this ability is in the terminating state. | Type| Description| | -------- | -------- | -| bool | The value **true** means that the ability is in terminating state, and **false** means the opposite.| +| boolean| The value **true** means that the ability is in the terminating state, and **false** means the opposite.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index c2bb08c5314a44dcf6f4ad9246e6ee08a313ecd8..545da5d468feefce2440a356812356e6206e11e3 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -1,6 +1,6 @@ # wantConstant -The **wantConstant** module provides the action, entity, and flags used in **Want** objects. +The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. > **NOTE** > @@ -23,15 +23,15 @@ Enumerates the action constants of the **Want** object. | ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | | ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | | ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | -| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides radio network settings, for example, Wi-Fi option. | +| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides wireless network settings, for example, Wi-Fi options. | | ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | | ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. | | ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. | -| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all clock alarms. | +| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all alarms. | | ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. | | ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | | ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | -| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS. | +| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. | | ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. | | ACTION_IMAGE_CAPTURE8+ | ohos.want.action.imageCapture | Action of launching the UI for photographing. | | ACTION_VIDEO_CAPTURE8+ | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 2b17d252af9d09d5519f36ece4306834e8085c5a..003a5efd92057dc7127b74aa35553f3220bd890e 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -49,7 +49,7 @@ Checks whether an application has been granted the specified permission. This AP | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to verify.| **Return value** @@ -105,7 +105,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl Grants a user granted permission to an application. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS @@ -143,7 +143,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS @@ -179,7 +179,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF Revokes a user granted permission given to an application. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS @@ -217,7 +217,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS @@ -253,7 +253,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g Obtains the flags of the specified permission of a given application. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, ohos.permission.GRANT_SENSITIVE_PERMISSIONS, or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md index f51fee8402c98f9c36e81f355df105a3154e0105..43786f3925b5277d3b806cf638ab7238fe40fd6b 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -23,23 +23,94 @@ import Want from '@ohos.application.Want'; | abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | -| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| +| flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).| | action | Read only | string | No | Action option. | -| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.js) module can be used to obtain application and bundle information. | +| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.md) module can be used to obtain application and bundle information. | | entities | Read only | Array\ | No | List of entities. | | moduleName9+ | Read only | string | No | Module to which the ability belongs.| **Example** -``` js - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry" // moduleName is optional. - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters uniquely identify an ability. - console.log("error.code = " + error.code) - }) -``` +- Basic usage + + ``` js + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Passing a file descriptor (FD) + + ``` js + var fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Passing **RemoteObject** data + + ``` js + class Stub extends rpc.RemoteObject { + constructor(des) { + if (typeof des == 'string') { + super(des); + } else { + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + if (code === 1) { + console.log('onRemoteRequest called') + let token = data.readInterfaceToken(); + let num = data.readInt(); + this.method(); + return true; + } + return false; + } + + method() { + console.log('method called'); + } + } + + var remoteObject = new Stub('want-test'); + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + "parameters": { + "keyRemoteObject":{"type":"RemoteObject", "value":remoteObject} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index 42974b5fd683af842146b53fec22022edca84de6..54264312fcc88ad0177473a7e4d256f566e6c2d2 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,6 +1,6 @@ # AbilityLifecycleCallback -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onAbilityWindowStageCreate**, and **onAbilityWindowStageDestroy**, to receive lifecycle state changes in the application context. +The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. > **NOTE** > @@ -30,9 +30,9 @@ Called when an ability is created. | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| -## AbilityLifecycleCallback.onAbilityWindowStageCreate +## AbilityLifecycleCallback.onWindowStageCreate -onAbilityWindowStageCreate(ability: Ability): void; +onWindowStageCreate(ability: Ability, windowStage: window.WindowStage): void; Called when the window stage of an ability is created. @@ -43,11 +43,44 @@ Called when the window stage of an ability is created. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| -## AbilityLifecycleCallback.onAbilityWindowStageDestroy +## AbilityLifecycleCallback.onWindowStageActive -onAbilityWindowStageDestroy(ability: Ability): void; +onWindowStageActive(ability: Ability, windowStage: window.WindowStage): void; + +Called when the window stage of an ability gains focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onWindowStageInactive + +onWindowStageInactive(ability: Ability, windowStage: window.WindowStage): void; + +Called when the window stage of an ability loses focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onWindowStageDestroy + +onWindowStageDestroy(ability: Ability, windowStage: window.WindowStage): void; Called when the window stage of an ability is destroyed. @@ -58,6 +91,7 @@ Called when the window stage of an ability is destroyed. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onAbilityDestroy @@ -132,12 +166,22 @@ Called when an ability is continued on another device. onAbilityCreate(ability){ console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); }, - onAbilityWindowStageCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageCreate ability:" + JSON.stringify(ability)); - }, - onAbilityWindowStageDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageDestroy ability:" + JSON.stringify(ability)); - }, + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + }, onAbilityDestroy(ability){ console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); }, diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index cf5291224477451554ea36e823ecedc0629cbfe0..16d5fd0c3d79d097bc8f78ef24cae8f91869b8e3 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -19,7 +19,7 @@ import AbilityContext from '@ohos.application.Ability' let context = this.context.createBundleContext(test); } } - ``` +``` ## Attributes @@ -53,15 +53,15 @@ Creates a context for a given application. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Application bundle name.| **Return value** -| Type| Description| -| -------- | -------- | -| Context | Context created.| + | Type| Description| + | -------- | -------- | + | Context | Context created.| **Example** @@ -87,15 +87,15 @@ Creates a context for a given HAP. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| moduleName | string | Yes| HAP name in the application.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | moduleName | string | Yes| HAP name in the application.| **Return value** -| Type| Description| -| -------- | -------- | -| Context | Context created.| + | Type| Description| + | -------- | -------- | + | Context | Context created.| **Example** @@ -123,16 +123,16 @@ Creates a context for a given HAP in an application. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| -| moduleName | string | Yes| HAP name in the application.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Application bundle name.| + | moduleName | string | Yes| HAP name in the application.| **Return value** -| Type| Description| -| -------- | -------- | -| Context | Context created.| + | Type| Description| + | -------- | -------- | + | Context | Context created.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 05ff78e77e6d6d54527148782b18d0dbca007cd6..1b2bd22548deeed3145803c1a3939e59399b904c 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t **Return value** - | Type| Description| - | -------- | -------- | - | Promise<number> | Size of the application memory.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Size of the application memory.| **Example** @@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | No| Size of the application memory.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | No| Size of the application memory.| **Example** @@ -155,7 +155,11 @@ Obtains the memory size of this application. This API uses an asynchronous callb console.log('startAbility result success:' + JSON.stringify(data)); }) ``` -## appManager.getProcessRunningInfos8+ +## appManager.getProcessRunningInfos(deprecated) + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. getProcessRunningInfos(): Promise\>; @@ -181,7 +185,11 @@ Obtains information about the running processes. This API uses a promise to retu }); ``` -## appManager.getProcessRunningInfos8+ +## appManager.getProcessRunningInfos(deprecated) + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. getProcessRunningInfos(callback: AsyncCallback\>): void; @@ -206,11 +214,62 @@ Obtains information about the running processes. This API uses an asynchronous c }) ``` +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(): Promise\>; + +Obtains information about the running processes. 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 process information.| + +**Example** + + ```js + app.getProcessRunningInformation().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(callback: AsyncCallback\>): void; + +Obtains information about the running processes. 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\> | No| Callback used to return the process information.| + +**Example** + + ```js + app.getProcessRunningInformation((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + ## appManager.registerApplicationStateObserver8+ registerApplicationStateObserver(observer: ApplicationStateObserver): number; -Registers the application state observer. +Registers an observer to listen for the state of all applications. **Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER @@ -222,7 +281,7 @@ Registers the application state observer. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observer | ApplicationStateObserver | No| Numeric code of the observer.| +| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| **Example** @@ -244,6 +303,48 @@ Registers the application state observer. const observerCode = app.registerApplicationStateObserver(applicationStateObserver); console.log('-------- observerCode: ---------', observerCode); + ``` + +## appManager.registerApplicationStateObserver9+ + +registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array): number; + +Registers an observer to listen for the state of a specified application. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| +| bundleNameList | Array | No| **bundleName** array to be registered for listening. The maximum value is 128.| + +**Example** + + ```js + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + } + } + var bundleNameList = ['bundleName1', 'bundleName2']; + const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); + console.log('-------- observerCode: ---------', observerCode); + ``` ## appManager.unregisterApplicationStateObserver8+ @@ -258,7 +359,7 @@ Deregisters the application state observer. This API uses an asynchronous callba **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observerId | number | No| Numeric code of the observer.| @@ -319,7 +420,7 @@ Deregisters the application state observer. This API uses a promise to return th getForegroundApplications(callback: AsyncCallback\>): void; -Obtains applications that run in the foreground. This API uses an asynchronous callback to return the result. +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -350,7 +451,7 @@ Obtains applications that run in the foreground. This API uses an asynchronous c getForegroundApplications(): Promise\>; -Obtains applications that run in the foreground. This API uses a promise to return the result. +Obtains applications that are running in the foreground. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -380,7 +481,7 @@ Obtains applications that run in the foreground. This API uses a promise to retu killProcessWithAccount(bundleName: string, accountId: number): Promise\ -Kills the process by bundle name and account ID. This API uses a promise to return the result. +Kills a process by bundle name and account ID. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES @@ -390,10 +491,10 @@ Kills the process by bundle name and account ID. This API uses a promise to retu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| Account ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Example** @@ -414,7 +515,7 @@ app.killProcessWithAccount(bundleName, accountId) killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void -Kills the process by bundle name and account ID. This API uses an asynchronous callback to return the result. +Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -424,11 +525,11 @@ Kills the process by bundle name and account ID. This API uses an asynchronous c **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| Account ID.| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -708,7 +809,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | bundleName8+ | string | Yes | No | Bundle name of an application. | | abilityName8+ | string | Yes | No | Ability name. | | uid8+ | number | Yes | No | User ID. | -| state8+ | number | Yes | No | Application information. | +| state8+ | number | Yes | No | Ability state. | | moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | | abilityType8+ | string | Yes | No | Ability type. | @@ -736,3 +837,16 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | uid9+ | Read only | number | No | User ID.| | processName9+ | Read only | string | No | Process name.| | bundleNames9+ | Read only | Array\ | No | **bundleName** array in the running processes.| + +## ApplicationStateObserver + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| [onForegroundApplicationChanged8+](#applicationstateobserveronforegroundapplicationchanged8) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | +| [onAbilityStateChanged8+](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | +| [onProcessCreated8+](#applicationstateobserveronprocesscreated8) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | +| [onProcessDied8+](#applicationstateobserveronprocessdied8) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index cbb0ff47c767fd26e499913f44ba88d7e6187f17..67b4a955e1cfe2d9bd557cc47fdc938b010a8de6 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -1,6 +1,6 @@ -# BackgroundTaskManager +# Background Task Management -This module provides background task management. +The **BackgroundTaskManager** module provides APIs to manage background tasks. If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. @@ -15,7 +15,7 @@ If an application has a service that can be intuitively perceived by users and n ## Modules to Import -``` +```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` @@ -144,12 +144,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ------------------------ | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ---------------------------------------- | +| 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).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -196,11 +196,11 @@ Requests a continuous task from the system. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ----------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ---------------------------------------- | +| 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).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** | Type | Description | @@ -245,10 +245,10 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------- | ---- | ---------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ---------------------------------------- | +| 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).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -276,9 +276,9 @@ Requests to cancel a continuous task. This API uses a promise to return the resu **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------- | ---- | --------- | -| context | [Context](js-apis-Context.md) | Yes | Application context.| +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ---------------------------------------- | +| 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).| **Return value** | Type | Description | @@ -314,14 +314,14 @@ Provides the information about the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| Name | Value| Description | -| ----------------------- | ------ | ------------------------------------------------------------ | -| DATA_TRANSFER | 1 | Data transfer. | -| AUDIO_PLAYBACK | 2 | Audio playback. | -| AUDIO_RECORDING | 3 | Audio recording. | -| LOCATION | 4 | Positioning and navigation. | -| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | -| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | -| WIFI_INTERACTION | 7 | WLAN-related.
This is a system API and cannot be called by third-party applications.| -| VOIP | 8 | Audio and video calls.
This is a system API and cannot be called by third-party applications.| -| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| DATA_TRANSFER | 1 | Data transfer. | +| AUDIO_PLAYBACK | 2 | Audio playback. | +| AUDIO_RECORDING | 3 | Audio recording. | +| LOCATION | 4 | Positioning and navigation. | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | +| WIFI_INTERACTION | 7 | WLAN-related.
This is a system API.| +| VOIP | 8 | Audio and video calls.
This is a system API. | +| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | 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 74ba45c52450241572aff5ab9cba2a55debd9124..3cb5f2792733b4ad88914023b7debb7354fa74b4 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,16 +1,11 @@ # AbilityInfo - +Unless otherwise specified, ability information is obtained through **GET_BUNDLE_DEFAULT**. > **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 ability information. - - +## AbilityInfo **System capability**: SystemCapability.BundleManager.BundleFramework @@ -25,24 +20,24 @@ Provides the ability information. | iconId | number | Yes | No | Ability icon ID. | | moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | | process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| -| targetAbility | string | Yes | No | Target ability that the ability alias points to. | -| backgroundModes | number | Yes | No | Background service mode of the ability. | +| targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| +| backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | | isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | -| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability. | -| type | AbilityType | Yes | No | Ability type. | +| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| +| type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | | orientation | DisplayOrientation | Yes | No | Ability display orientation. | | launchMode | LaunchMode | Yes | No | Ability launch mode. | -| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.| +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| | deviceTypes | Array\ | Yes | No | Device types supported by the ability. | | deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | -| readPermission | string | Yes | No | Permission required for reading the ability data. | -| writePermission | string | Yes | No | Permission required for writing data to the ability. | -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | -| uri | string | Yes | No | URI of the ability. | +| readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| +| writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing **GET_ABILITY_INFO_WITH_APPLICATION**.| +| uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| | 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. | +| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| +| metaData8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| +| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| | 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-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md new file mode 100644 index 0000000000000000000000000000000000000000..7c86528db55ea364316caaa927b29a90f88b253c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -0,0 +1,100 @@ +# BundleInstaller + +The **BundleInstaller** module provides APIs for installing, updating, and deleting bundles on devices. + +> **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. + +## System Capability + +SystemCapability.BundleManager.BundleFramework + +## BundleInstaller.install + +install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; + +Installs bundles. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleFilePaths | Array<string> | Yes | Paths where the bundles are stored. Each path should point to a relative directory of the current application's data directory.| +| param | [InstallParam](#installparam) | Yes | Parameters required for the installation or uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status. | + +## BundleInstaller.uninstall + +uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; + +Uninstalls a bundle. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparam) | Yes | Parameters required for the installation or uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| + +## BundleInstaller.recover + +recover(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; + +Recovers a bundle. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparam) | Yes | Parameters required for the installation or uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| + +## InstallParam + +Describes the parameters required for bundle installation or uninstall. + + **System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Description | +| ----------- | ------- | ------------------ | +| userId | number | User ID. | +| installFlag | number | Installation flag. | +| isKeepData | boolean | Whether data is kept.| + +## InstallStatus + +Describes the bundle installation status. + + **System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | +| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. | +| statusMessage | string | Yes | No | Installation or uninstall status message.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index ede83cd6de76637220005f0821471c0141c9721f..205c9f15192c4c2c9abfcb08b1f1ae156d7baf75 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -1,14 +1,14 @@ # ElementName +The **ElementName** module provides the element name information. + > **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 +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..7b932cacbc2195e8c52976aa80e71bd3b638921d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @@ -0,0 +1,20 @@ +# LauncherAbilityInfo + +The **LauncherAbilityInfo** module provides information about a launcher ability. + +> **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. + +## LauncherAbilityInfo + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| --------------- | ---------------------------------------------------- | ---- | ---- | ------------------------------------ | +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.| +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. | +| labelId | number | Yes | No | Label ID of the launcher ability. | +| iconId | number | Yes | No | Icon ID of the launcher ability. | +| userId | number | Yes | No | User ID of the launcher ability. | +| installTime | number | Yes | No | Time when the launcher ability is installed. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md new file mode 100644 index 0000000000000000000000000000000000000000..4ebc8d40516c596de2977ea19583e019cce2ac1f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -0,0 +1,19 @@ +# PermissionDef + +The **PermissionDef** module provides permission details defined in the configuration file. + +> **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. + +## **PermissionDef** + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | -------------- | +| permissionName | string | Yes | No | Name of the permission. | +| grantMode | number | Yes | No | Grant mode of the permission.| +| labelId | number | Yes | No | Label ID of the permission. | +| descriptionId | number | Yes | No | Description ID of the permission. | + diff --git a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..8b2cf350047aa0d4c8e165b71b030f3816f6f75f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -0,0 +1,41 @@ +# ShortcutInfo + +The **ShortcutInfo** module provides shortcut information defined in the configuration file. + +> **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. + +## ShortcutWant + +Describes the information about the target to which the shortcut points. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------ | ---- | ---- | -------------------- | +| targetBundle | string | Yes | No | Target bundle of the shortcut.| +| targetModule9+ | string | Yes | No | Target module of the shortcut. | +| targetClass | string | Yes | No | Target class required by the shortcut.| + +## ShortcutInfo + +Describes the shortcut attribute information. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | +| id | string | Yes | No | ID of the application to which the shortcut belongs. | +| bundleName | string | Yes | No | Name of the bundle that contains the shortcut. | +| hostAbility | string | Yes | No | Local ability information of the shortcut. | +| icon | string | Yes | No | Icon of the shortcut. | +| iconId8+ | number | Yes | No | Icon ID of the shortcut. | +| label | string | Yes | No | Label of the shortcut. | +| labelId8+ | number | Yes | No | Label ID of the shortcut. | +| disableMessage | string | Yes | No | Message displayed when the shortcut is disabled. | +| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | +| isStatic | boolean | Yes | No | Whether the shortcut is static. | +| isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut.| +| isEnabled | boolean | Yes | No | Whether the shortcut is enabled. | +| moduleName9+ | string | Yes | No | Module name of the shortcut. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..4210ac52230c5e86855c8afacd7c442999efdea6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -0,0 +1,17 @@ +# RemoteAbilityInfo + +The **RemoteAbilityInfo** module provides information about a remote ability. + +> **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. + +## RemoteAbilityInfo + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the ability. | +| label | string | Yes | No | Label of the ability. | +| icon | string | Yes | No | Icon of the ability.| 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 adf54efbe8e95058c353a049211cec7c20e72ae3..296b8a58c2e89677eed23ee377c7568603429646 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -4,7 +4,7 @@ The relational database (RDB) manages data based on relational models. With the This module provides the following RDB-related functions: -- [RdbPredicates](#rdbpredicates): predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. - [RdbStore](#rdbstore): provides APIs for managing an RDB store. > **NOTE**
@@ -166,14 +166,14 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates -Specifies a remote device on the network during distributed database synchronization. +Connects to the specified remote devices on the network during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| devices | Array<string> | Yes| ID of the remote device to specify.| +| devices | Array<string> | Yes| IDs of the remote devices in the same network.| **Return value** | Type| Description| @@ -948,6 +948,8 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. +Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). + ### insert @@ -977,7 +979,7 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { console.log("Failed to insert data"); return; } - console.log("Inserted data, rowId = " + rowId); + console.log("Inserted data successfully, rowId = " + rowId); }) ``` @@ -1011,7 +1013,7 @@ const valueBucket = { } let promise = rdbStore.insert("EMPLOYEE", valueBucket) promise.then((rowId) => { - console.log("Inserted data, rowId = " + rowId); + console.log("Inserted data successfully, rowId = " + rowId); }).catch((status) => { console.log("Failed to insert data"); }) @@ -1056,10 +1058,10 @@ const valueBucket3 = { var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { if (status) { - console.log("bathInsert failed, status = " + status); + console.log("Failed to batch insert data, status = " + status); return; } - console.log("bathInsert is successful, the number of values that were inserted = " + insertNum); + console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); }) ``` @@ -1106,9 +1108,9 @@ const valueBucket3 = { var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { - console.log("bathInsert is successful, the number of values that were inserted = " + insertNum); + console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); }).catch((status) => { - console.log("bathInsert failed, status = " + status); + console.log("Failed to batch insert data, status = " + status); }) ``` @@ -1116,14 +1118,14 @@ promise.then((insertNum) => { update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void -Updates data 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 update in the RDB store. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. 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 invoked to return the number of rows updated.| @@ -1158,7 +1160,7 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| 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.| +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. 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** @@ -1187,7 +1189,7 @@ promise.then(async (ret) => { ### update9+ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void -Updates data 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 @@ -1222,7 +1224,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> -Updates data 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 @@ -1520,7 +1522,7 @@ Queries data from the RDB store of a remote device based on specified conditions | -------- | -------- | -------- | -------- | | device | string | Yes| Network ID of the remote device.| | table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions for querying data.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| @@ -1553,7 +1555,7 @@ Queries data from the RDB store of a remote device based on specified conditions | -------- | -------- | -------- | -------- | | device | string | Yes| Network ID of the remote device.| | table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions for querying data.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| **Return value** @@ -1580,7 +1582,7 @@ promise.then((resultSet) => { querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void -Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. +Queries data in the RDB store using the specified SQL statement. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1588,7 +1590,7 @@ Queries data using the specified SQL statement. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** @@ -1608,7 +1610,7 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> -Queries data using the specified SQL statement. This API uses a promise to return the result. +Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1616,7 +1618,7 @@ Queries data using the specified SQL statement. This API uses a promise to retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **Return value** | Type| Description| @@ -1648,7 +1650,7 @@ Executes an SQL statement that contains specified arguments but returns no value | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| | bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| -| callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** ```js @@ -1658,7 +1660,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { console.info("Failed to execute SQL, err: " + err) return } - console.info('Create table done.') + console.info('Created table successfully.') }) ``` @@ -1680,14 +1682,14 @@ Executes an SQL statement that contains specified arguments but returns no value **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise that returns no value.| +| Promise<void> | Promise used to return the result.| **Example** ```js const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" let promise = rdbStore.executeSql(SQL_CREATE_TABLE) promise.then(() => { - console.info('Create table done.') + console.info('Created table successfully.') }).catch((err) => { console.info("Failed to execute SQL, err: " + err) }) @@ -1785,7 +1787,7 @@ rdbStore.backup("dbBackup.db", function(err) { console.info('Failed to back up data, err: ' + err) return } - console.info('Backup successful.') + console.info('Backed up data successfully.') }) ``` @@ -1811,7 +1813,7 @@ Backs up an RDB store. This API uses a promise to return the result. ```js let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(()=>{ - console.info('Backup successful.') + console.info('Backed up data successfully.') }).catch((err)=>{ console.info('Failed to back up data, err: ' + err) }) @@ -1838,7 +1840,7 @@ rdbStore.restore("dbBackup.db", function(err) { console.info('Failed to restore data, err: ' + err) return } - console.info('Restore successful.') + console.info('Restored data successfully.') }) ``` @@ -1864,7 +1866,7 @@ Restores an RDB store from a backup file. This API uses a promise to return the ```js let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(()=>{ - console.info('Restore successful.') + console.info('Restored data successfully.') }).catch((err)=>{ console.info('Failed to restore data, err: ' + err) }) @@ -1924,7 +1926,7 @@ let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) promise.then(() => { console.info("Set distributed tables successfully.") }).catch((err) => { - console.info("Failed to set distributed tables, err: " + err) + console.info('Failed to set distributed tables, err: ' + err) }) ``` @@ -1932,7 +1934,7 @@ promise.then(() => { obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses an asynchronous callback to return the result. +Obtains the distributed table name for a remote device based on the local table name. This API uses an asynchronous callback to return the result. The distributed table name is required when the RDB store of a remote device is queried. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1961,7 +1963,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, obtainDistributedTableName(device: string, table: string): Promise<string> -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result. +Obtains the distributed table name for a remote device based on the local table name. This API uses a promise to return the result. The distributed table name is required when the RDB store of a remote device is queried. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -2003,7 +2005,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret | -------- | -------- | -------- | -------- | | mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| -| callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +| callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Example** ```js @@ -2042,7 +2044,7 @@ Synchronizes data between devices. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<Array<[string, number]>> | Promise used to return the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +| Promise<Array<[string, number]>> | Promise used to return the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index 52af89ae7faa9fd20a28a62f959f4a3f39340ced..1d10f56aeb69e13d2f329bfc18f56127667ef930 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -119,7 +119,7 @@ helper.on( off(type: 'dataChange', uri: string, callback?: AsyncCallback\): void -Unregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Deregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -647,7 +647,7 @@ Deletes one or more data records from the database. This API uses an asynchronou ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -662,7 +662,7 @@ DAHelper.delete( ## DataAbilityHelper.delete -delete(uri: string, predicates: dataAbility.DataAbilityPredicates): Promise\ +delete(uri: string, predicates?: dataAbility.DataAbilityPredicates): Promise\; Deletes one or more data records from the database. This API uses a promise to return the result. @@ -685,7 +685,7 @@ Deletes one or more data records from the database. This API uses a promise to r ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -719,7 +719,7 @@ Updates data records in the database. This API uses an asynchronous callback to ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -741,7 +741,7 @@ DAHelper.update( ## DataAbilityHelper.update -update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates): Promise\ +update(uri: string, valuesBucket: rdb.ValuesBucket, predicates?: dataAbility.DataAbilityPredicates): Promise\; Updates data records in the database. This API uses a promise to return the result. @@ -765,7 +765,7 @@ Updates data records in the database. This API uses a promise to return the resu ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -806,7 +806,7 @@ Queries data in the database. This API uses an asynchronous callback to return t ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -825,7 +825,7 @@ DAHelper.query( ## DataAbilityHelper.query -query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates): Promise\ +query(uri: string, columns?: Array\, predicates?: dataAbility.DataAbilityPredicates): Promise\; Queries data in the database. This API uses a promise to return the result. @@ -849,7 +849,7 @@ Queries data in the database. This API uses a promise to return the result. ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -876,7 +876,7 @@ Calls the extended API of the Data ability. This API uses a promise to return th | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx" | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | | arg | string | Yes |Parameter to pass. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | @@ -912,7 +912,7 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx" | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | | arg | string | Yes |Parameter to pass. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | @@ -932,8 +932,107 @@ dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", " console.info('Operation succeeded: ' + data); }); ``` + +## DataAbilityHelper.executeBatch + +executeBatch(uri: string, operations: Array\, callback: AsyncCallback\>): void; + +Operates data in the database. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------- | ---- | ------------------------------------------------ | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | +| callback | AsyncCallback\> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. | + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Select the operations to be performed on the database according to the DataAbilityOperation array. +let op=new Array(); +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); +dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + err); + return; + } + console.info('Operation succeeded: ' + data); +}); +``` + +## DataAbilityHelper.executeBatch + +executeBatch(uri: string, operations: Array\): Promise\>; + +Operates data in the database. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | -------------------------------| ---- | ------------------------------------------------ | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | + +**Return value** + +| Type| Description| +|------ | ------- | +|Promise\> | Promise used to return the result of each operation in the **DataAbilityResult** array.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Select the operations to be performed on the database according to the DataAbilityOperation array. +let op=new Array(); +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); +dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility",op ).then((data) => { + console.info('Operation succeeded: ' + data); +}).catch((error) => { + console.error('Operation failed. Cause: ' + error); +}); + +``` + ## PacMap +[key: string]: number | string | boolean | Array\ | null; + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + | Name| Type| Mandatory| Description| | ------ | ------ | ------ | ------ | | [key: string] | number \| string \| boolean \| Array\ \| null | Yes| Data stored in key-value pairs.| + +## DataAbilityOperation + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Readable | Writable | Mandatory| Description | +| -------- | -------- | -------- | -------- | --------| -------- | +| uri | string | Yes | No | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| type | featureAbility.DataAbilityOperationType | Yes | No | Yes | Operation type. | +| valuesBucket? | rdb.ValuesBucket | Yes | No | No | Data value to set. | +| valueBackReferences? | rdb.ValuesBucket | Yes | No | No | **ValuesBucket** object that contains a set of key-value pairs. | +| predicates? | dataAbility.DataAbilityPredicates | Yes | No | No | Predicates to set. If no predicate is set, all data records are displayed. | +| predicatesBackReferences? | Map\ | Yes | No | No | Back references of the predicates. | +| interrupted? | boolean | Yes | No | No | Whether batch operations can be interrupted. | +| expectedCount? | number | Yes | No | No | Expected number of rows to be updated or deleted. | + +## DataAbilityResult + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Readable | Writable | Mandatory | Description | +| -------- | -------- | -------- | -------- | -------- | -------- | +| uri? | string | Yes | No | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| count? | number | Yes | No | No | Number of rows affected by the operation. | diff --git a/en/application-dev/reference/apis/js-apis-dispatchInfo.md b/en/application-dev/reference/apis/js-apis-dispatchInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..5f476f34bd9ed8c08fc0e033243c1f4fb55ca23c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-dispatchInfo.md @@ -0,0 +1,16 @@ +# DispatchInfo + +The **DispatchInfo** module provides dispatch information. + +> **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. + +## DispatchInfo + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | ------------------------ | +| verison | string | Yes | No | Version of the API to dispatch.| +| dispatchAPI | string | Yes | No | API to dispatch. | diff --git a/en/application-dev/reference/apis/js-apis-errorManager.md b/en/application-dev/reference/apis/js-apis-errorManager.md new file mode 100644 index 0000000000000000000000000000000000000000..a06e1650bd6f3614a33c58dd092b55451d0a0db8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-errorManager.md @@ -0,0 +1,139 @@ +# ErrorManager + +The **ErrorManager** module provides APIs for registering and deregistering error observers. + +> **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 +``` +import errorManager from '@ohos.application.errorManager' +``` + +## ErrorManager.registerErrorObserver + +registerErrorObserver(observer: ErrorObserver): number; + +Registers an error observer. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | [ErrorObserver](#errorobserver) | No| Numeric code of the observer.| + +**Example** + +```js +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + } +} +errorManager.registerErrorObserver(observer) + .then((data) => { + console.log('----------- registerErrorObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- registerErrorObserver fail ----------', err); + }) + +``` + +## ErrorManager.unregisterErrorObserver + +unregisterErrorObserver(observerId: number, callback: AsyncCallback\): void; + +Deregisters an error observer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | No| Numeric code of the observer.| +| callback | AsyncCallback\ | No| Callback used to return the result.| + +**Example** + +```js +var observerId = 100; + +function unregisterErrorObserverCallback(err) { + if (err) { + console.log('------------ unregisterErrorObserverCallback ------------', err); + } +} +errorManager.unregisterErrorObserver(observerId, unregisterErrorObserverCallback); + +``` + +## ErrorManager.unregisterErrorObserver + +unregisterErrorObserver(observerId: number): Promise\; + +Deregisters an error observer. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | No| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var observerId = 100; +errorManager.unregisterErrorObserver(observerId) +.then((data) => { + console.log('----------- unregisterErrorObserver success ----------', data); +}) +.catch((err) => { + console.log('----------- unregisterErrorObserver fail ----------', err); +}) + +``` + +## ErrorObserver + +onUnhandledException(errMsg: string): void; + +Called when an unhandled exception occurs in the JS runtime. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| errMsg | string | No| Message and error stack trace about the exception.| + +**Example** + +```js +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + } +} +errorManager.registerErrorObserver(observer) + .then((data) => { + console.log('----------- registerErrorObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- registerErrorObserver fail ----------', err); + }) + +``` diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md index daea33dbb50edf3aec50c84eee9795339bd9c43a..1540e538e1bcc8f53165a3fd277e60f76e73a7a1 100644 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ b/en/application-dev/reference/apis/js-apis-formextension.md @@ -35,15 +35,15 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| + | Name| Type | Mandatory| Description | + | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | + | want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| **Return value** -| Type | Description | -| ------------------------------------------------------------ | ----------------------------------------------------------- | -| [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| + | Type | Description | + | ------------------------------------------------------------ | ----------------------------------------------------------- | + | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| **Example** @@ -72,9 +72,9 @@ Called to notify the widget provider that a temporary widget has been converted **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------ | -| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | formId | string | Yes | ID of the widget that requests to be converted to a normal one.| **Example** @@ -96,9 +96,9 @@ Called to notify the widget provider that a widget has been updated. After obtai **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| formId | string | Yes | ID of the widget that requests to be updated.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | formId | string | Yes | ID of the widget that requests to be updated.| **Example** @@ -127,9 +127,9 @@ Called to notify the widget provider of the change of visibility. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ---------------------------- | -| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| + | Name | Type | Mandatory| Description | + | --------- | ------------------------- | ---- | ---------------------------- | + | newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| **Example** @@ -162,10 +162,10 @@ Called to instruct the widget provider to receive and process the widget event. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ---------------------- | -| formId | string | Yes | ID of the widget that requests the event.| -| message | string | Yes | Event message. | + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ---------------------- | + | formId | string | Yes | ID of the widget that requests the event.| + | message | string | Yes | Event message. | **Example** @@ -187,9 +187,9 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| formId | string | Yes | ID of the widget to be destroyed.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | formId | string | Yes | ID of the widget to be destroyed.| **Example** @@ -211,9 +211,9 @@ Called when the configuration of the environment where the ability is running is **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| **Example** @@ -235,9 +235,9 @@ Called when the widget provider receives the status query result of a widget. By **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| **Example** @@ -250,3 +250,40 @@ Called when the widget provider receives the status query result of a widget. By } } ``` + +## FormExtension.onShare + +onShare?(formId: string): {[key: string]: any}; + +Called by the widget provider to receive shared widget data. + +This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type | Description | + | ------------------------------------------------------------ | ----------------------------------------------------------- | + | {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| + +**Example** + + ```js + class MyFormExtension extends FormExtension { + onShare(formId) { + console.log('FormExtension onShare, formId:' + formId); + let wantParams = { + "temperature":"20", + "time":"2022-8-8 09:59", + }; + return wantParams; + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-formextensioncontext.md b/en/application-dev/reference/apis/js-apis-formextensioncontext.md index f2e1fe143fbac2991698d2dd4244d88b23b0ebd5..7cd19e0e0f9a5d4ae906abd1a6d469893c1e95e0 100644 --- a/en/application-dev/reference/apis/js-apis-formextensioncontext.md +++ b/en/application-dev/reference/apis/js-apis-formextensioncontext.md @@ -2,13 +2,32 @@ The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for Form Extension abilities. -You can use the APIs of this module to start abilities. +You can use the APIs of this module to start Form Extension abilities. > **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. +## Usage + +Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtension** instance. +```js +import FormExtension from '@ohos.application.FormExtension'; +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onCreate() { + let dataObj1 = { + temperature:"11c", + "time":"11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +} + +``` + ## FormExtensionContext.startAbility startAbility(want: Want, callback: AsyncCallback<void>): void @@ -64,7 +83,7 @@ Starts an ability. This API uses a promise to return the result. | Type | Description | | ------------ | ---------------------------------- | -| Promise\ | Promise used to return the result.| +| Promise<void< | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-formprovider.md index 81855948f4994b85d601763ffe5e817a175d3733..fbe8907aed6b59d005f027af62ec4d0b0ec9a141 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-formprovider.md @@ -189,6 +189,7 @@ Obtains the application's widget information that meets a filter criterion on th **Example** ```js +import formInfo from '@ohos.application.formInfo'; const filter : formInfo.FormInfoFilter = { moduleName : "entry" }; @@ -224,6 +225,7 @@ Obtains the application's widget information on the device. This API uses a prom **Example** ```js +import formInfo from '@ohos.application.formInfo'; const filter : formInfo.FormInfoFilter = { moduleName : "entry" }; @@ -236,13 +238,13 @@ formProvider.getFormsInfo(filter).then((data) => { ## requestPublishForm9+ -requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback<string>): <void>; +requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void; Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -276,13 +278,13 @@ SystemCapability.Ability.Form ## requestPublishForm9+ -requestPublishForm(want: Want, callback: AsyncCallback<string>): <void>; +requestPublishForm(want: Want, callback: AsyncCallback<string>): void; Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -317,9 +319,9 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData Requests to publish a widget to the widget host. This API uses a promise to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -360,6 +362,8 @@ Checks whether a widget can be published to the widget host. This API uses an as **System capability**: SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type | Mandatory| Description | @@ -402,6 +406,8 @@ Checks whether a widget can be published to the widget host. This API uses a pro **System capability**: SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type | Description | diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 77002020139fbdb2aada0cb1141a0f2840a9f250..dff8251fcc345a2e8fb24b4fcafee582357951b0 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -106,6 +106,7 @@ media.createVideoPlayer().then((video) => { createAudioRecorder(): AudioRecorder Creates an **AudioRecorder** instance to control audio recording. +Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder @@ -126,6 +127,7 @@ let audioRecorder = media.createAudioRecorder(); createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): void Creates a **VideoRecorder** instance in asynchronous mode. This API uses a callback to return the result. +Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -155,6 +157,7 @@ media.createVideoRecorder((error, video) => { createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)> Creates a **VideoRecorder** instance in asynchronous mode. This API uses a promise to return the result. +Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -272,14 +275,15 @@ For details about the audio playback demo, see [Audio Playback Development](../. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| 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. 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. | -| state | [AudioState](#audiostate) | Yes | No | Audio playback state. | - +| Name | Type | Readable| Writable| Description | +| ------------------------------- | ----------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.INTERNET (The latter is required only when online resources are used.)| +| fdSrc9+ | [AVFileDescriptor](#interruptmode9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
If the file is an independent music file, use **src=fd://xx**.

**Required permissions**: ohos.permission.READ_MEDIA| +| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | +| audioInterruptMode9+ | [InterruptMode](#interruptmode9) | Yes | Yes | Audio interruption mode. | +| currentTime | number | Yes | No | Current audio playback position, in ms. | +| duration | number | Yes | No | Audio duration, in ms. | +| state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| ### play play(): void @@ -501,7 +505,7 @@ Subscribes to the audio buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | +| 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** @@ -590,7 +594,7 @@ audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' e on(type: 'timeUpdate', callback: Callback\): void -Subscribes to the 'timeUpdate' event. +Subscribes to the **'timeUpdate'** event. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -598,7 +602,7 @@ Subscribes to the 'timeUpdate' event. | Name | Type | Mandatory| Description | | -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'timeUpdate' in this case.
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** @@ -618,7 +622,7 @@ audioPlayer.seek(30000); // Seek to 30000 ms. on(type: 'error', callback: ErrorCallback): void -Subscribes to the audio playback error event. +Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -626,13 +630,13 @@ Subscribes to the audio playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
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** ```js -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}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. @@ -646,13 +650,38 @@ Enumerates the audio playback states. You can obtain the state through the **sta **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| Name | Type | Description | -| ------------------ | ------ | -------------- | -| idle | string | The audio player is idle.| -| playing | string | Audio playback is in progress.| -| paused | string | Audio playback is paused.| -| stopped | string | Audio playback is stopped.| -| error8+ | string | Audio playback is in the error state. | +| Name | Type | Description | +| ------------------ | ------ | ---------------------------------------------- | +| idle | string | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.| +| playing | string | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered. | +| paused | string | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered. | +| stopped | string | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered. | +| error8+ | string | Audio playback is in the error state. | + +## AVFileDescriptor9+ + +Describes audio and video file resources. It is used to specify a particular resource for playback based on its offset and length within a file. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| fd | number | Yes | Resource handle, which is obtained by calling **resourceManager.getRawFileDescriptor**. | +| offset | number | Yes | Resource offset, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.| +| length | number | Yes | Resource length, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.| + +## InterruptMode9+ + +Describes the audio interruption mode. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +| Name | Default Value| Description | +| ---------------------------- | ------ | ---------- | +| SHARE_MODE | 0 | Shared mode.| +| INDEPENDENT_MODE| 1 | Independent mode. | ## VideoPlayer8+ @@ -666,13 +695,16 @@ 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. 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.| +| 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: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.INTERNET (The latter is required only when online resources are used.)| +| fdSrc9+ | [AVFileDescriptor](#interruptmode9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
**Note**:
**Required permissions**: ohos.permission.READ_MEDIA| | 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. | +| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | +| audioInterruptMode9+ | [InterruptMode](#interruptmode9) | Yes | Yes | Audio interruption mode. | +| currentTime8+ | number | Yes | No | Current video playback position, in ms. | +| duration8+ | number | Yes | No | Video duration, in ms. The value **-1** indicates the live mode. | | state8+ | [VideoPlayState](#videoplaystate8) | Yes | No | Video playback state. | -| width8+ | number | Yes | No | Video width. | -| height8+ | number | Yes | No | Video height. | +| width8+ | number | Yes | No | Video width, in pixels. | +| height8+ | number | Yes | No | Video height, in pixels. | ### setDisplaySurface8+ @@ -1334,7 +1366,7 @@ videoPlayer.setSpeed(speed).then() => { 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+). +Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1362,7 +1394,7 @@ videoPlayer.selectBitrate(bitrate, (err, result) => { 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+). +Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1401,7 +1433,7 @@ Subscribes to the video playback completion event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ----------------------------------------------------------- | -| type | string | Yes | Event type, which is 'playbackCompleted' in this case.| +| type | string | Yes | Event type, which is **'playbackCompleted'** in this case. | | callback | function | Yes | Callback invoked when the event is triggered. | **Example** @@ -1424,7 +1456,7 @@ Subscribes to the video buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | +| 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** @@ -1448,7 +1480,7 @@ Subscribes to the frame rendering start event. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'startRenderFrame' in this case.| +| type | string | Yes | Event type, which is **'startRenderFrame'** in this case. | | callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** @@ -1471,7 +1503,7 @@ Subscribes to the video width and height change event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'videoSizeChanged' in this case.| +| 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** @@ -1487,7 +1519,7 @@ videoPlayer.on('videoSizeChanged', (width, height) => { on(type: 'error', callback: ErrorCallback): void -Subscribes to the video playback error event. +Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1495,7 +1527,7 @@ Subscribes to the video playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
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** @@ -1506,12 +1538,12 @@ videoPlayer.on('error', (error) => { // Set the 'error' event callback. console.info(`video error called, errCode is ${error.code}`); // Print the error code. console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); -videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. +videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. ``` -### on('availableBitrateCollected')9+ +### on('availableBitratesCollect')9+ -on(type: 'availableBitrateCollected', callback: (bitrates: Array) => void): void +on(type: 'availableBitratesCollect', callback: (bitrates: Array\) => void): void Subscribes to the video playback bit rate reporting event. @@ -1521,15 +1553,15 @@ Subscribes to the video playback bit rate reporting event. | 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. | +| type | string | Yes | Event type, which is **'availableBitratesCollect'** 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) => { +videoPlayer.on('availableBitratesCollect', (bitrates) => { for (let i = 0; i < bitrates.length; i++) { - console.info('case availableBitrateCollected bitrates: ' + bitrates[i]); // Print bit rates. + console.info('case availableBitratesCollect bitrates: ' + bitrates[i]); // Print bit rates. } }); ``` @@ -1574,6 +1606,17 @@ Enumerates the video playback speeds, which can be passed in the **setSpeed** AP | SPEED_FORWARD_1_75_X | 3 | Plays the video at 1.75 times the normal speed.| | SPEED_FORWARD_2_00_X | 4 | Plays the video at 2.00 times the normal speed.| +## VideoScaleType9+ + +Enumerates the video scale modes. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +| Name | Default Value| Description | +| ---------------------------- | ------ | ---------- | +| VIDEO_SCALE_TYPE_FIT | 0 | The video will be stretched to fit the window.| +| VIDEO_SCALE_TYPE_FIT_CROP| 1 | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped. | + ## MediaDescription8+ ### [key : string] : Object @@ -1765,7 +1808,7 @@ Subscribes to the audio recording events. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| 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.| +| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- 'reset': 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** @@ -1781,41 +1824,41 @@ let audioRecorderConfig = { uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. location : { latitude : 30, longitude : 130}, } -audioRecorder.on('error', (error) => { // Set the error event callback. +audioRecorder.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}`); }); -audioRecorder.on('prepare', () => { // Set the prepare event callback. +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the start event callback. + audioRecorder.start(); // Start recording and trigger the 'start' event callback. }); -audioRecorder.on('start', () => { // Set the start event callback. +audioRecorder.on('start', () => { // Set the 'start' event callback. console.log('audio recorder start success'); }); -audioRecorder.on('pause', () => { // Set the pause event callback. +audioRecorder.on('pause', () => { // Set the 'pause' event callback. console.log('audio recorder pause success'); }); -audioRecorder.on('resume', () => { // Set the resume event callback. +audioRecorder.on('resume', () => { // Set the 'resume' event callback. console.log('audio recorder resume success'); }); -audioRecorder.on('stop', () => { // Set the stop event callback. +audioRecorder.on('stop', () => { // Set the 'stop' event callback. console.log('audio recorder stop success'); }); -audioRecorder.on('release', () => { // Set the release event callback. +audioRecorder.on('release', () => { // Set the 'release' event callback. console.log('audio recorder release success'); }); -audioRecorder.on('reset', () => { // Set the reset event callback. +audioRecorder.on('reset', () => { // Set the 'reset' event callback. console.log('audio recorder reset success'); }); -audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the prepare event callback. +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. ``` ### on('error') on(type: 'error', callback: ErrorCallback): void -Subscribes to the audio recording error event. +Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder @@ -1823,18 +1866,18 @@ Subscribes to the audio recording error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
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** ```js -audioRecorder.on('error', (error) => { // Set the error event callback. +audioRecorder.on('error', (error) => { // Set the 'error' event callback. console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. }); -audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the error event callback. +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` ## AudioRecorderConfig @@ -1978,7 +2021,7 @@ prepare(config: VideoRecorderConfig): Promise\; Sets video recording parameters in asynchronous mode. This API uses a promise to return the result. -**Required permissions:** ohos.permission.MICROPHONE and ohos.permission.CAMERA +**Required permissions:** ohos.permission.MICROPHONE **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2109,7 +2152,7 @@ start(callback: AsyncCallback\): void; Starts video recording in asynchronous mode. This API uses a callback to return the result. -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. +This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2138,7 +2181,7 @@ start(): Promise\; Starts video recording in asynchronous mode. This API uses a promise to return the result. -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. +This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2273,7 +2316,7 @@ stop(callback: AsyncCallback\): void; Stops video recording in asynchronous mode. This API uses a callback to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2302,7 +2345,7 @@ stop(): Promise\; Stops video recording in asynchronous mode. This API uses a promise to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2381,7 +2424,7 @@ reset(callback: AsyncCallback\): void; Resets video recording in asynchronous mode. This API uses a callback to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2410,7 +2453,7 @@ reset(): Promise\; Resets video recording in asynchronous mode. This API uses a promise to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2435,7 +2478,7 @@ videoRecorder.reset().then(() => { on(type: 'error', callback: ErrorCallback): void -Subscribes to the video recording error event. +Subscribes to video recording error events. After an error event is reported, you must handle the event and exit the recording. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2443,13 +2486,13 @@ Subscribes to the video recording error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
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** ```js -videoRecorder.on('error', (error) => { // Set the error event callback. +videoRecorder.on('error', (error) => { // Set the 'error event' callback. console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. @@ -2485,7 +2528,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)
**Required permissions**: ohos.permission.READ_MEDIA| ## AudioSourceType9+ diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index b981d28061d45feb313dbaf7ea0709d6f198e0e8..50057062701f1ddbe0b058dc79e957c1a47e63a3 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -362,6 +362,88 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r }); ``` +## missionManager.getLowResolutionMissionSnapShot9+ + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback\): void; + +Obtains the low-resolution snapshot of a given mission. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + +**Example** + + ```js + import missionManager from '@ohos.application.missionManager' + + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { + console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) + ``` + + +## missionManager.getLowResolutionMissionSnapShot9+ + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\; + +Obtains the low-resolution snapshot of a given mission. This API uses a promise to return the result. + +**Required permission**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| + +**Example** + + ```js + import missionManager from '@ohos.application.missionManager' + + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ + console.log(err); + }); + ``` + ## missionManager.lockMission diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md new file mode 100644 index 0000000000000000000000000000000000000000..eb7d01dda3b5bcf8c88a45981d661aacf6d4e4f4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -0,0 +1,1820 @@ +# Standard NFC Tag Technologies + +The **nfctech** module provides methods for reading and writing tags that use different Near-Field Communication (NFC) technologies. + +> **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** + +```js +import tag from '@ohos.nfc.tag'; +``` + +## NfcATag + +Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. **NfcATag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcATag**. + +### NfcATag.getSak + +getSak(): number + +Obtains the SAK value of this NFC-A tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | SAK value obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let sak = tag.getNfcATag(taginfo).getSak(); +console.log("sak:" +sak); +``` + +### NfcATag.getAtqa + +getAtqa(): number[] + +Obtains the ATQA value of this NFC-A tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | ATQA value obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let atqa = tag.getNfcATag(taginfo).getAtqa(); +console.log("atqa:" +atqa); +``` + +## NfcBTag + +Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. **NfcBTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcBTag**. + +### NfcBTag.getRespAppData + +getRespAppData(): number[] + +Obtains the application data of this NFC-B tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | Application data obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let appData = tag.getNfcBTag(taginfo).getRespAppData(); +console.log("appData:" +appData); +``` + +### NfcBTag.getRespProtocol + +getRespProtocol(): number[] + +Obtains protocol information of this NFC-B tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | Protocol information obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let protocol = tag.getNfcBTag(taginfo).getRespProtocol(); +console.log("appData:" +protocol); +``` + +## NfcFTag + +Provides access to NFC-F(JIS 6319-4) properties and I/O operations. **NfcFTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcFTag**. + +### NfcFTag.getSystemCode + +getSystemCode(): number[] + +Obtains the system code from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | System code obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let systemCode = tag.getNfcFTag(taginfo).getSystemCode(); +console.log("systemCode:" +systemCode); +``` + +### NfcFTag.getPmm + +getPmm(): number[] + +Obtains the PMm (consisting of the IC code and manufacturer parameters) information from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | PMm information obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let pmm = tag.getNfcFTag(taginfo).getPmm(); +console.log("pmm:" +pmm); +``` + +## NfcVTag + +Provides access to NFC-V (ISO 15693) properties and I/O operations. **NfcVTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcVTag**. + +### NfcvTag.getResponseFlags + +getResponseFlags(): number + +Obtains the response flags from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Response flags obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let flags = tag.getNfcVTag(taginfo).getResponseFlags(); +console.log("flags:" +flags); +``` + +### NfcvTag.getDsfId + +getDsfId(): number + +Obtains the data storage format identifier (DSFID) from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | DSFID obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let dsfId = tag.getNfcVTag(taginfo).getDsfId(); +console.log("dsfId:" +dsfId); +``` + +## IsoDepTag9+ + +Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. **IsoDepTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **IsoDepTag**. + +### IsoDepTag.getHistoricalBytes9+ + +getHistoricalBytes(): string + +Obtains the historical bytes of this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| string | Historical bytes obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let historicalBytes = tag.getIsoDepTag(taginfo).getHistoricalBytes(); +console.log("historicalBytes:" +historicalBytes); +``` + +### IsoDepTag.getHiLayerResponse9+ + +getHiLayerResponse(): string + +Obtains the HiLayer response of this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| string | HiLayer response obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let hiLayerResponse = tag.getIsoDepTag(taginfo).getHiLayerResponse(); +console.log("hiLayerResponse:" +hiLayerResponse); +``` + +### IsoDepTag.isExtendedApduSupported9+ + +isExtendedApduSupported(): Promise<boolean> + +Checks whether an extended application protocol data unit (APDU) is supported. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<boolean> | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.getIsoDepTag(taginfo).isExtendedApduSupported().then(function (has) { + console.log('has: ' + has) +}) +``` + +### IsoDepTag.isExtendedApduSupported9+ + +isExtendedApduSupported(callback: AsyncCallback\): void + +Checks whether an extended application protocol data unit (APDU) is supported. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.getIsoDepTag(taginfo).isExtendedApduSupported(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +## NdefTag9+ + +Provides access to the tags in the NFC Data Exchange Format (NDEF). **NdefTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NdefTag**. + +### NdefTag.createNdefMessage9+ + +createNdefMessage(data: string): [NdefMessage](#ndefmessage9) + +Creates an NDEF message using raw bytes. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Raw bytes of the string type.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](#ndefmessage9) | NDEF message created.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(data); +``` + +## NdefMessage9+ + +### NdefMessage.getNdefRecords9+ + +getNdefRecords(): [NdefRecord](#ndefrecord9)[ ] + +Obtains all NDEF records. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9)[ ] | All records obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefRecord = tag.NdefTag(taginfo).getNdefRecords(); +``` + +## NdefRecord9+ + +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| tnf | number | UID of the tag.| +| [rtdType](#rtdtype9) | string | NFC Record Type Definition (RTD) supported by the tag.| +| id | string | Additional information about the tag.| +| payload | string | RF discovery ID of the tag.| + +## RtdType9+ + +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| RTD_TEXT | 'T' | Text information.| +| RTD_URI | 'U' | Network address, email, or phone number.| + +### NdefTag.createNdefMessage9+ + +createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) + +Creates an NDEF message using the NDEF records. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| ndefRecords | [NdefRecord](#ndefrecord9)[] | Yes| A list of NDEF records.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](#ndefmessage9) | NDEF message created.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(ndefRecords); +``` + +### NdefTag.getNdefTagType9+ + +getNdefTagType(): NfcForumType + +Obtains the type of this NDEF tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NfcForumType](#nfcforumtype9) | NDEF tag type obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NfcForumType = tag.NdefTag(taginfo).getNdefTagType(); +``` + +### NdefTag.getNdefMessage9+ + +getNdefMessage(): NdefMessage + +Obtains the NDEF message from the tag discovered. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](#ndefmessage9) | NDEF message created.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefMessage = tag.NdefTag(taginfo).getNdefMessage(); +``` + +### NdefTag.isNdefWritable9+ + +isNdefWritable(): Promise<boolean> + +Checks whether the NDEF tag is writable. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<boolean> | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).isNdefWritable().then(function (has) { + console.log(JSON.stringify(has)) +}) +``` + +### NdefTag.isNdefWritable9+ + +isNdefWritable(callback: AsyncCallback<boolean>): void; + +Checks whether the NDEF tag is writable. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).isNdefWritable(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### NdefTag.readNdef9+ + +readNdef(): Promise\ + +Reads the NDEF message from this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).readNdef().then(function (ndefMessage) { + console.log(JSON.stringify(ndefMessage)) +}) +``` + +### NdefTag.readNdef9+ + +readNdef(callback: AsyncCallback\<[NdefMessage](#ndefmessage9)>): void + +Reads the NDEF message from this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).readNdef(function (error, ndefMessage) { + console.log(JSON.stringify(error)) + console.log('ndefMessage: ' + ndefMessage) +}) +``` + +### NdefTag.writeNdef9+ + +writeNdef(msg: NdefMessage): Promise\; + +Write an NDEF message to this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| msg | NdefMessage | Yes | NDEF message to write.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +NdefTag.writeNdef(msg).then(function (netHandle) { + console.log(JSON.stringify(netHandle)) +}) +``` + +### NdefTag.writeNdef9+ + +writeNdef(msg: NdefMessage, callback: AsyncCallback\): void + +Write an NDEF message to this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| msg | NdefMessage | Yes | NDEF message to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).write(msg, function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### NdefTag.canSetReadOnly9+ + +canSetReadOnly(): Promise\ + +Checks whether this NDEF tag can be set to read-only. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<boolean> | Promise used to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).canSetReadOnly().then(function (has) { + console.log(JSON.stringify(has)) +}) +``` + +### NdefTag.canSetReadOnly9+ + +canSetReadOnly()(callback: AsyncCallback<boolean>): void; + +Checks whether this NDEF tag can be set to read-only. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).canSetReadOnly(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### NdefTag.setReadOnly9+ + +setReadOnly(): Promise\ + +Sets this NDEF tag to read-only. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<number> | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).setReadOnly().then(function (errcode) { + console.log(JSON.stringify(errcode)) +}) +``` + +### NdefTag.setReadOnly9+ + +setReadOnly(callback: AsyncCallback): void + +Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).setReadOnly(function (error, errcode) { + console.log(JSON.stringify(error)) + console.log('has: ' + errcode) +}) +``` + +### NdefTag.getNdefTagTypeString9+ + +getNdefTagTypeString(type: [NfcForumType](#nfcforumtype9)): string + +Converts the NFC Forum Type to a byte array defined in the NFC Forum. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| type | [NfcForumType](#nfcforumtype9) | Yes | NFC Forum Type.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| string | Byte array obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let ndefTypeString= tag.NdefTag(taginfo).getNdefTagTypeString(type); +``` + +## NfcForumType9+ + +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| NFC_FORUM_TYPE_1 | 1 | NFC Forum Type 1.| +| NFC_FORUM_TYPE_2 | 2 | NFC Forum Type 2.| +| NFC_FORUM_TYPE_3 | 3 | NFC Forum Type 3.| +| NFC_FORUM_TYPE_4 | 4 | NFC Forum Type 4.| +| MIFARE_CLASSIC | 101 | MIFARE Classic.| + +## MifareClassicTag 9+ + +Provides access to MIFARE Classic properties and I/O operations. **MifareClassicTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **MifareClassicTag**. + +### MifareClassicTag.authenticateSector9+ + +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ + +Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector to authenticate.| +| key | number[]| Yes | Key (6 bytes) used for authentication.| +| isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If the authentication is successful, **true** is returned. Otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key).then(function (isKeyA) { + console.log(JSON.stringify(isKeyA)) + }) +``` + +### MifareClassicTag.authenticateSector9+ + +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback): void + +Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector to authenticate.| +| key | number[]| Yes | Key (6 bytes) used for authentication.| +| isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key, function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### MifareClassicTag.readSingleBlock9+ + +readSingleBlock(blockIndex: number): Promise\ + +Reads a block on the tag. The size of a block is 16 bytes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to read.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the block data read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex).then(function (data){ + console.log('data: ' + data) + }) +``` + +### MifareClassicTag.readSingleBlock9+ + +readSingleBlock(blockIndex: number, callback: AsyncCallback\): void + +Reads a block on the tag. The size of a block is 16 bytes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex, function (error, data) { + console.log(JSON.stringify(error)) + console.log('data: ' + data) +}) +``` + +### MifareClassicTag.writeSingleBlock9+ + +writeSingleBlock(blockIndex: number, data: string): Promise\ + +Writes data to a block on the tag. The size of a block is 16 bytes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the target block.| +| data | string | Yes | Data to write.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.writeSingleBlock9+ + +writeSingleBlock(blockIndex: number, data: string, callback: AsyncCallback\): void + +Writes data to a block on the tag. The size of a block is 16 bytes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the target block.| +| data | string | Yes | Data to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.incrementBlock9+ + +incrementBlock(blockIndex: number, value: number): Promise\ + +Increments a block with data. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to increment.| +| value | number | Yes | Block data to increment. The value is a non-negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.incrementBlock9+ + +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void + +Increments a block with data. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to increment.| +| value | number | Yes | Block data to increment. The value is a non-negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.decrementBlock9+ + +decrementBlock(blockIndex: number, value: number): Promise\ + +Decrements a block with data. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to decrement.| +| value | number | Yes | Block data to decrement. The value is a non-negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.decrementBlock9+ + +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void + +Decrements a block with data. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to decrement.| +| value | number | Yes | Block data to decrement. The value is a non-negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.transferToBlock9+ + +transferToBlock(blockIndex: number): Promise\ + +Copies data from the register to a block. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the destination block.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js + +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).transferToBlock(blockIndex).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.transferToBlock + +transferToBlock(blockIndex: number, callback: AsyncCallback\): void + +Copies data from the register to a block. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the destination block.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).transferToBlock(blockIndex, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.restoreFromBlock9+ + +restoreFromBlock(blockIndex: number): Promise\ + +Copies data from a block to the register. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the source block.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js + +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.restoreFromBlock9+ + +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void + +Copies data from a block to the register. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the source block.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.getSectorCount9+ + +getSectorCount(): number + +Obtains the number of sectors in this MIFARE Classic tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Number of sectors obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let setorCount = tag.MifareClassicTag(taginfo).getSectorCount(); +``` + +### MifareClassicTag.getBlockCountInSector9+ + +getBlockCountInSector(sectorIndex: number): number + +Obtains the number of blocks in a sector. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Number of blocks obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let blockNumber = tag.MifareClassicTag(taginfo).getBlockCountInSector(sectorIndex); +``` + +### MifareClassicTag.getType9+ + +getType(): [MifareClassicType](#mifareclassictype9) + +Obtains the type of this MIFARE Classic tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [MifareClassicType](#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let type = tag.MifareClassicTag(taginfo).getType(); +``` + +### MifareClassicTag.getTagSize9+ + +getTagSize(): number + +Obtains the tag size (in bytes). For details, see [MifareTagSize](#mifaretagsize9). + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Tag size obtained, in bytes. For details, see [MifareTagSize](#mifaretagsize9).| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let size = tag.MifareClassicTag(taginfo).getTagSize(); +``` + +## MifareClassicType9+ + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKNOWN | -1 | Unknown type.| +| TYPE_CLASSIC | 0 | MIFARE Classic.| +| TYPE_PLUS | 1 | MIFARE Plus.| +| TYPE_PRO | 2 | MIFARE Pro.| + +## MifareTagSize9+ + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| MC_SIZE_MINI | 320 | Each tag has five sectors, and each sector has four blocks.| +| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has four blocks.| +| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has four blocks.| +| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has four blocks.| + +### MifareClassicTag.isEmulatedTag9+ + +isEmulatedTag(): boolean + +Checks whether the tag is an emulated tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean |Returns **true** if the tag is an emulated tag; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let isEmulated = tag.MifareClassicTag(taginfo).isEmulatedTag(); +``` + +### MifareClassicTag.getBlockIndex9+ + +getBlockIndex(sectorIndex: number): number + +Obtains the first block of a sector. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Index of the first block obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let index = tag.MifareClassicTag(taginfo).getBlockIndex(sectorIndex); +``` + +### MifareClassicTag.getSectorIndex9+ + +getSectorIndex(blockIndex: number): number + +Obtains the index of a sector that contains the specified block. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block contained in the sector.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Index of the sector obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let index = tag.MifareClassicTag(taginfo).getSectorIndex(blockIndex); +``` + +## MifareUltralightTag9+ + +Provides access to MIFARE Ultralight properties and I/O operations. **MifareUltralightTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **MifareUltralightTag**. + +### MifareUltralightTag.readMultiplePages9+ + +readMultiplePages(pageIndex: number): Promise\ + +Reads multiple pages. The size of each page is 4 bytes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| pageIndex | number | Yes | Indexes of the pages to read.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the data read.| + +**Example** + +```js + +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex).then(function (data){ + console.log("data: " + data) + }) +``` + +### MifareUltralightTag.readMultiplePages9+ + +readMultiplePages(pageIndex: number, callback: AsyncCallback\): void + +Reads multiple pages. The size of each page is 4 bytes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| pageIndex | number | Yes | Indexes of the pages to read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the data read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +### MifareUltralightTag.writeSinglePages9+ + +writeSinglePages(pageIndex: number, data: string): Promise\ + +Writes a page of data. The size of each page is 4 bytes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| pageIndex | number | Yes | Index of the page.| +| data | string | Yes | Data to write.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareUltralightTag.writeSinglePages9+ + +writeSinglePages(pageIndex: number, data: string, callback: AsyncCallback\): void + +Writes a page of data. The size of each page is 4 bytes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------ | +| pageIndex | number | Yes | Index of the page.| +| data | string | Yes | Data to write.| +| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareUltralightTag.getType9+ + +getType(): MifareUltralightType + +Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](#mifareultralighttype9). + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| MifareUltralightType | Type of the MIFARE Ultralight tag. For details, see [MifareUltralightType](#mifareultralighttype9).| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let type = tag.MifareUltralightType(taginfo).getType(); +``` + +### MifareUltralightType9+ + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKOWN | -1 | Unknown type.| +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| +| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| + +## NdefFormatableTag9+ + +Provides methods for operating NDEF formattable tags. **NdefFormatableTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NdefFormatableTag**. + +### NdefFormatableTag.format9+ + +format(message: [NdefMessage](#ndefmessage9)): Promise\ + +Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).format(message).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### NdefFormatableTag.format9+ + +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void + +Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| +| callback: AsyncCallback\ | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).format(message, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### NdefFormatableTag.formatReadOnly9+ + +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ + +Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).formatReadOnly(message).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### NdefFormatableTag.formatReadOnly9+ + +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void + +Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| +| callback: AsyncCallback\ | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).formatReadOnly(message, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 7f83f0250c209dbd6b5d57970fe7beb8d9b9a494..8f88d00f0d246628e3669ae376da04191efedb92 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -68,29 +68,30 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| -| callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return a **PixelMap** object. | **Example** ```js - var ScreenshotOptions = { - "screenRect": { - "left": 200, - "top": 100, - "width": 200, - "height": 200}, - "imageSize": { - "width": 300, - "height": 300}, - "rotation": 0, - "displayId": 0 + var screenshotOptions = { + "screenRect": { + "left": 200, + "top": 100, + "width": 200, + "height": 200}, + "imageSize": { + "width": 300, + "height": 300}, + "rotation": 0, + "displayId": 0 }; - screenshot.save(ScreenshotOptions, (err, data) => { - if (err) { - console.error('Failed to save the screenshot. Error: ' + JSON.stringify(err)); - return; - } - console.info('Screenshot saved. Data: ' + JSON.stringify(data)); + screenshot.save(screenshotOptions, (err, pixelMap) => { + if (err) { + console.log('Failed to save screenshot: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. }); ``` @@ -114,12 +115,12 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis | Type | Description | | ----------------------------- | ----------------------------------------------- | -| Promise<image.PixelMap> | Promise used to return a **PixelMap** object.| +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return a **PixelMap** object.| **Example** ```js - var ScreenshotOptions = { + var screenshotOptions = { "screenRect": { "left": 200, "top": 100, @@ -131,10 +132,11 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis "rotation": 0, "displayId": 0 }; - let promise = screenshot.save(ScreenshotOptions); - promise.then(() => { - console.log('screenshot save success'); + let promise = screenshot.save(screenshotOptions); + promise.then((pixelMap) => { + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. }).catch((err) => { - console.log('screenshot save fail: ' + JSON.stringify(err)); + console.log('Failed to save screenshot: ' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-service-extension-ability.md b/en/application-dev/reference/apis/js-apis-service-extension-ability.md index 388657b05dce3f05601cc88123ff2d64adbf127b..388b4308555f8dc061bfa62da40fd4dc5d97cfee 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-ability.md @@ -23,9 +23,9 @@ None. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate @@ -40,9 +40,9 @@ Called when a Service Extension ability is created to initialize the service log **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -88,10 +88,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| -| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** @@ -116,15 +116,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Return value** -| Type| Description| -| -------- | -------- | -| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| + | Type| Description| + | -------- | -------- | + | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| **Example** @@ -158,9 +158,9 @@ Called when this Service Extension ability is disconnected. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -184,16 +184,16 @@ Called when this Service Extension ability is reconnected. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** ```js class ServiceExt extends ServiceExtension { - onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); + onReconnect(want) { + console.log('onReconnect, want:' + want.abilityName); } } ``` @@ -202,7 +202,7 @@ Called when this Service Extension ability is reconnected. onConfigurationUpdated(config: Configuration): void; -Called when the configuration of this Service Extension ability is updated. + Called when the configuration of this Service Extension ability is updated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -210,9 +210,9 @@ Called when the configuration of this Service Extension ability is updated. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| **Example** @@ -236,9 +236,9 @@ Dumps the client information. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| params | Array\ | Yes| Parameters in the form of a command.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | params | Array\ | Yes| Parameters in the form of a command.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index 241a8bf17f94a3362fe6d12d4662b139c4c4cd8b..cb56fdccb85fd5aa96e161df2f86fbc1a5573b2d 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -26,7 +26,7 @@ Before using the **ServiceExtensionContext** module, you must define a child cla startAbility(want: Want, callback: AsyncCallback<void>): void; -Starts an ability. This API uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -36,8 +36,8 @@ Starts an ability. This API uses a callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| - | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the API is successfully called.| + | want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Example** @@ -64,14 +64,14 @@ Starts an ability. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| + | want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -92,7 +92,7 @@ Starts an ability. This API uses a promise to return the result. startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void -Starts an ability. This API uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -102,7 +102,7 @@ Starts an ability. This API uses a callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| @@ -136,8 +136,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -169,8 +169,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -206,10 +206,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js @@ -245,7 +251,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -275,7 +281,13 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -310,8 +322,8 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -344,8 +356,14 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -369,7 +387,7 @@ Starts a new Service Extension ability with the account ID specified. This API u stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops Service Extension abilities in the same application. This API uses an asynchronous callback to return the result. +Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -379,7 +397,7 @@ Stops Service Extension abilities in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -399,7 +417,7 @@ Stops Service Extension abilities in the same application. This API uses an asyn stopServiceExtensionAbility(want: Want): Promise\; -Stops Service Extension abilities in the same application. This API uses a promise to return the result. +Stops a Service Extension ability in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -409,7 +427,13 @@ Stops Service Extension abilities in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -432,7 +456,7 @@ Stops Service Extension abilities in the same application. This API uses a promi stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops Service Extension abilities in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -444,8 +468,8 @@ Stops Service Extension abilities in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -466,7 +490,7 @@ Stops Service Extension abilities in the same application with the account ID sp stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops Service Extension abilities in the same application with the account ID specified. This API uses a promise to return the result. +Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -478,8 +502,14 @@ Stops Service Extension abilities in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -503,7 +533,7 @@ Stops Service Extension abilities in the same application with the account ID sp terminateSelf(callback: AsyncCallback<void>): void; -Terminates this ability. This API uses a callback to return the result. +Terminates this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -513,7 +543,7 @@ Terminates this ability. This API uses a callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the API is successfully called.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Example** @@ -537,7 +567,7 @@ Terminates this ability. This API uses a promise to return the result. | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -563,7 +593,7 @@ Connects this ability to a Service ability. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to connect to, such as the ability name and bundle name.| + | want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| **Return value** @@ -601,8 +631,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | ConnectOptions | No| Remote object instance.| **Return value** @@ -633,7 +663,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect disconnectAbility(connection: number, callback:AsyncCallback<void>): void; -Disconnects this ability from the Service ability. This API uses a callback to return the result. +Disconnects this ability from the Service ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -644,7 +674,7 @@ Disconnects this ability from the Service ability. This API uses a callback to r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | connection | number | Yes| Number returned after **connectAbility** is called.| - | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the API is successfully called.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Example** @@ -676,7 +706,7 @@ Disconnects this ability from the Service ability. This API uses a promise to re | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -689,3 +719,41 @@ Disconnects this ability from the Service ability. This API uses a promise to re console.log('failed:' + JSON.stringify(error)); }); ``` + +## ServiceExtensionContext.startAbilityByCall + +startAbilityByCall(want: Want): Promise<Caller>; + +Starts an ability in the background and obtains the caller interface for communication. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, including the ability name, module name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Caller> | Promise used to return the caller object to communicate with.| + +**Example** + + ```js + let caller = undefined; + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + console.log('Caller GetCaller Get ' + caller); + }).catch((e) => { + console.log('Caller GetCaller error ' + e); + }); + ``` + diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 9371381ea8d39f48410d925bd0b28b441f6a9be6..3cb8380f9f35b7fa584f09b0d88c5fb45e0c22fe 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -21,7 +21,7 @@ getUriSync(name: string): string Obtains the URI of a data item. -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** @@ -50,7 +50,7 @@ getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: strin Obtains the value of a data item. -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** | Name| Type| Mandatory| Description| @@ -87,7 +87,7 @@ If the specified data item exists in the database, the **setValueSync** method u **Required permissions**: ohos.permission.MODIFY_SETTINGS -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-system-mediaquery.md b/en/application-dev/reference/apis/js-apis-system-mediaquery.md index f2057a86685a5d212e84caf27e69468b8169c267..841cebeb1da0380128d3704650a0aaf9ef095d5f 100644 --- a/en/application-dev/reference/apis/js-apis-system-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-system-mediaquery.md @@ -1,7 +1,9 @@ # Media Query +The **mediaquery** module provides different styles for different media types. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + +> **NOTE** > > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.mediaquery`](js-apis-mediaquery.md) instead. > - 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. @@ -38,11 +40,7 @@ Creates a **MediaQueryList** object based on the query condition. **Example** ``` -export default { - matchMedia() { - var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); - }, -} +var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); ``` ## MediaQueryEvent @@ -95,11 +93,16 @@ Adds a listener for this **MediaQueryList** object. The listener must be added b | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | -------------- | -| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the matching condition changes.| +| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the query condition changes.| **Example** ``` +function maxWidthMatch(e){ + if(e.matches){ + // do something + } +} mMediaQueryList.addListener(maxWidthMatch); ``` @@ -116,10 +119,15 @@ Removes the listener for this **MediaQueryList** object. | Name | Type | Mandatory | Description | | -------- | --------------------------------- | ---- | -------------- | -| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the matching condition changes.| +| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the query condition changes.| **Example** ``` +function maxWidthMatch(e){ + if(e.matches){ + // do something + } +} mMediaQueryList.removeListener(maxWidthMatch); ``` diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md new file mode 100644 index 0000000000000000000000000000000000000000..5ed3760a0cf3664cc6991a73489dd7f53ab9d83b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -0,0 +1,127 @@ +# Standard NFC Tag Session + +The **tagSession** module provides common APIs for establishing connections and transferring 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** + +```js +import tag from '@ohos.nfc.tag'; +``` + +## tagSession + +Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md). + +A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. + +The specific method varies with the NFC tag technology in use. For details, see [nfcTag](js-apis-nfcTag.md). + +### tagSession.connectTag + +connectTag(): boolean; + +Connects to this tag. + +Call this method to set up a connection before reading data from or writing data to a tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); +console.log("isNfcConnected:" +isNfcConnected); +``` + +### tagSession.reset() + +reset(): void + +Resets the connection to this tag and restores the default timeout duration for writing data to the tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let reset = tag.getXXXTag(taginfo).reset(); +console.log("reset:" +reset); +``` + +### tagSession.isTagConnected + +isTagConnected(): boolean + +Checks whether the tag is connected. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the tag is connected; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an Object given by nfc service when tag is dispatched. +let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); +console.log("isTagConnected:" +isTagConnected); +``` + +### tagSession.getMaxSendLength + +getMaxSendLength(): number + +Obtains the maximum length of the data that can be sent to the tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Maximum data length obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); +console.log("mazSendLen:" +mazSendLen); +``` diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index b5eab0ff1825741b77cf81ae966c499aff4c1398..76bba2f5b15c6a9da9b2f4bb4f5201f4552a9cbd 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -25,21 +25,24 @@ Enumerates the window types. | Name | Value| Description | | ----------------- | ------ | ------------------ | -| TYPE_APP | 0 | Application subwindow. This type can be used only in the FA model.| +| TYPE_APP | 0 | Application subwindow.
**Model restriction**: This API can be used only in the FA model.| | TYPE_SYSTEM_ALERT | 1 | System alert window.| -| 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.| +| TYPE_INPUT_METHOD9+ | 2 | Input method window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_STATUS_BAR9+ | 3 | Status bar.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_PANEL9+ | 4 | Notification panel.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_KEYGUARD9+ | 5 | Lock screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_VOLUME_OVERLAY9+ | 6 | Volume bar.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_NAVIGATION_BAR9+ | 7 | Navigation bar.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_FLOAT9+ | 8 | Floating window.
**Model restriction**: This API can be used only in the stage model.
**Required permissions**: ohos.permission.SYSTEM_FLOAT_WINDOW| +| TYPE_WALLPAPER9+ | 9 | Wallpaper.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_DESKTOP9+ | 10 | Home screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_LAUNCHER_RECENT9+ | 11 | Recent tasks screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_LAUNCHER_DOCK9+ | 12 | Dock bar on the home screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_VOICE_INTERACTION9+ | 13 | Voice assistant.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_POINTER9+ | 14 | Mouse.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_FLOAT_CAMERA9+ | 15 | Floating camera window.
**Model restriction**: This API can be used only in the stage model.
**Required permissions**: ohos.permission.SYSTEM_FLOAT_WINDOW| +| TYPE_DIALOG9+ | 16 | Modal window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_SCREENSHOT9+ | 17 | Screenshot window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| ## AvoidAreaType7+ @@ -58,7 +61,7 @@ Enumerates the types of the area where the window cannot be displayed. Enumerates the window modes. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -74,7 +77,7 @@ This is a system API and cannot be called by third-party applications. Enumerates the window layout modes. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -119,11 +122,26 @@ Enumerates the window orientations. | AUTO_ROTATION_LANDSCAPE_RESTRICTED | 10 | Switched-determined auto rotation in the horizontal direction.| | LOCKED | 11 | Locked.| +## BlurStyle9+ + +Enumerates the window blur styles. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Value | Description | +| ------- | ---- | -------------------- | +| OFF | 0 | Blur disabled. | +| THIN | 1 | Thin blur.| +| REGULAR | 2 | Regular blur.| +| THICK | 3 | Thick blur.| + ## SystemBarRegionTint8+ Describes the callback for a single system bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -139,7 +157,7 @@ This is a system API and cannot be called by third-party applications. Describes the callback for the current system bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -169,7 +187,7 @@ Describes the area where the window cannot be displayed. | Name | Type | Readable| Writable| Description | | ---------- | ------------- | ---- | ---- | ------------------ | -| visible9+ | boolean | Yes | Yes | Whether the area is visible.| +| visible9+ | boolean | Yes | Yes | Whether the window can be displayed in the area.| | 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.| @@ -192,20 +210,20 @@ Describes the window properties. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| ------------------------------- | ------------------------- | ---- | ---- | -------------------------------------------- | -| 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.
**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`. | +| Name | Type | Readable| Writable| Description | +| ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | +| 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.
**NOTE**
This property 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`. | +| isRoundCorner(deprecated) | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| +| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | ## ColorSpace8+ @@ -218,13 +236,58 @@ Describes the color gamut mode. | DEFAULT | 0 | Default color gamut mode.| | WIDE_GAMUT | 1 | Wide color gamut mode. | +## ScaleOptions9+ + +Describes the scale parameters. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | -------------------------------------------------- | +| x | number | No | Yes | Scale factor of the x-axis. The default value is `1.0`. | +| y | number | No | Yes | Scale factor of the y-axis. The default value is `1.0`. | +| pivotX | number | No | Yes | X coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| pivotY | number | No | Yes | Y coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| + +## RotateOptions9+ + +Describes the rotation parameters. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | -------------------------------------------------- | +| x | number | No | Yes | Rotation angle around the x-axis. The default value is `0.0`. | +| y | number | No | Yes | Rotation angle around the y-axis. The default value is `0.0`. | +| z | number | No | Yes | Rotation angle around the z-xis. The default value is `0.0`. | +| pivotX | number | No | Yes | X coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| pivotY | number | No | Yes | Y coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| + +## TranslateOptions9+ + +Describes the translation parameters. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------- | +| x | number | No | Yes | Distance to translate along the x-axis. The default value is `0.0`.| +| y | number | No | Yes | Distance to translate along the y-axis. The default value is `0.0`.| +| z | number | No | Yes | Distance to translate along the z-axis. The default value is `0.0`.| + ## window.create7+ create(id: string, type: WindowType, callback: AsyncCallback<Window>): void Creates a subwindow. This API uses an asynchronous callback to return the result. -This API can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -240,13 +303,14 @@ This API can be used only in the FA model. ```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.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('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); +}); ``` ## window.create7+ @@ -255,7 +319,7 @@ create(id: string, type: WindowType): Promise<Window> Creates a subwindow. This API uses a promise to return the result. -This API can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -279,7 +343,7 @@ 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)); + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); }); @@ -300,7 +364,7 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | 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 subwindow created. | **Example** @@ -308,11 +372,11 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). 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)); + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); return; } windowClass = data; - console.info('Window created. Data: ' + JSON.stringify(data)); + console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); windowClass.resetSize(500, 1000); }); ``` @@ -337,7 +401,7 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Type | Description | | -------------------------------- | --------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the window created. | +| Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** @@ -345,8 +409,8 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). 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)); + windowClass = data; + console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); }); @@ -377,7 +441,7 @@ var windowClass = null; return; } windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)); + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }); ``` @@ -408,7 +472,7 @@ var windowClass = null; let promise = window.find("alertWindow"); promise.then((data)=> { windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)); + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); }); @@ -420,7 +484,7 @@ 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 can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -450,7 +514,7 @@ getTopWindow(): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. -This API can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -540,7 +604,7 @@ 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -548,7 +612,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------- | -| id | number | Yes | ID of the [display](js-apis-display.md#display). | +| id | number | Yes | ID of the [display](js-apis-display.md#display).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -578,7 +642,7 @@ 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -620,7 +684,7 @@ 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -647,7 +711,7 @@ 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -673,7 +737,7 @@ setWindowLayoutMode(mode: WindowLayoutMode, callback: AsyncCallback<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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -697,7 +761,7 @@ 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -730,7 +794,7 @@ on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): v Enables listening for properties changes of the status bar and navigation bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -755,7 +819,7 @@ off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >) Disables listening for properties changes of the status bar and navigation bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -784,7 +848,7 @@ hide (callback: AsyncCallback<void>): void Hides this window. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -802,7 +866,7 @@ windowClass.hide((err, data) => { console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); return; } - console.info('window hidden. data: ' + JSON.stringify(data)); + console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); }) ``` @@ -812,7 +876,7 @@ hide(): Promise<void> Hides this window. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -827,12 +891,67 @@ This is a system API and cannot be called by third-party applications. ```js let promise = windowClass.hide(); promise.then((data)=> { - console.info('window hidden. Data: ' + JSON.stringify(data)); + console.info('Succeeded in hiding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); }) ``` +### hideWithAnimation9+ + +hideWithAnimation(callback: AsyncCallback<void>): void + +Hides this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +windowClass.hideWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in hiding the window with animation. data: ' + JSON.stringify(data)); +}) +``` + +### hideWithAnimation9+ + +hideWithAnimation(): Promise<void> + +Hides this window and plays an animation during the process. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = windowClass.hideWithAnimation(); +promise.then((data)=> { + console.info('Succeeded in hiding the window with animation. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); +}) +``` + ### show7+ show(callback: AsyncCallback<void>): void @@ -884,6 +1003,61 @@ promise.then((data)=> { }) ``` +### showWithAnimation9+ + +showWithAnimation(callback: AsyncCallback<void>): void + +Shows this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +windowClass.showWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}) +``` + +### showWithAnimation9+ + +showWithAnimation(): Promise<void> + +Shows this window and plays an animation during the process. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = windowClass.showWithAnimation(); +promise.then((data)=> { + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); +}) +``` + ### destroy7+ destroy(callback: AsyncCallback<void>): void @@ -959,7 +1133,7 @@ windowClass.moveTo(300, 300, (err, data)=>{ console.error('Failed to move the window. Cause:' + JSON.stringify(err)); return; } - console.info('Window moved. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); }); ``` @@ -990,7 +1164,7 @@ Moves this window. This API uses a promise to return the result. ```js let promise = windowClass.moveTo(300, 300); promise.then((data)=> { - console.info('Window moved. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); }) @@ -1020,7 +1194,7 @@ windowClass.resetSize(500, 1000, (err, data) => { console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); return; } - console.info('Window size changed. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); }); ``` @@ -1050,19 +1224,23 @@ Changes the size of this window. This API uses a promise to return the result. ```js let promise = windowClass.resetSize(500, 1000); promise.then((data)=> { - console.info('Window size changed. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); }); ``` -### setWindowType7+ +### setWindowType(deprecated) setWindowType(type: WindowType, callback: AsyncCallback<void>): void Sets the type of this window. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. +> +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1086,13 +1264,17 @@ windowClass.setWindowType(type, (err, data) => { }); ``` -### setWindowType7+ +### setWindowType(deprecated) setWindowType(type: WindowType): Promise<void> Sets the type of this window. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. +> +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1183,7 +1365,7 @@ Obtains the area where this window cannot be displayed, for example, the system | 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.| +| 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** @@ -1211,7 +1393,7 @@ Obtains the area where this window cannot be displayed, for example, the system | 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.| +| 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** @@ -1368,13 +1550,14 @@ Sets whether to display the status bar and navigation bar in this window. This A **Example** ```js -var names = ["status", "navigation"]; +// In this example, the status bar and navigation bar are not displayed. +var names = []; windowClass.setSystemBarEnable(names, (err, data) => { if (err.code) { - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); }); ``` @@ -1401,12 +1584,13 @@ Sets whether to display the status bar and navigation bar in this window. This A **Example** ```js -var names = ["status", "navigation"]; +// In this example, the status bar and navigation bar are not displayed. +var names = []; let promise = windowClass.setSystemBarEnable(names); promise.then((data)=> { - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); }); ``` @@ -1611,7 +1795,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1620,14 +1804,14 @@ This API can be used only in the stage model. | 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.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | 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 + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -1649,7 +1833,7 @@ 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1658,7 +1842,7 @@ This API can be used only in the stage model. | 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.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** @@ -1670,7 +1854,7 @@ This API can be used only in the stage model. ```ts class myAbility extends Ability { - storage : LocalStorage + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -1786,9 +1970,9 @@ windowClass.off('windowSizeChange'); on(type: 'systemAvoidAreaChange', callback: Callback<[AvoidArea](#avoidarea7)>): void Enables listening for changes to the area where the window cannot be displayed. -> **NOTE** +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. > -> This API is deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1812,9 +1996,9 @@ windowClass.on('systemAvoidAreaChange', (data) => { off(type: 'systemAvoidAreaChange', callback?: Callback<[AvoidArea](#avoidarea7)>): void Disables listening for changes to the area where the window cannot be displayed. -> **NOTE** +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. > -> This API is deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1850,8 +2034,8 @@ Enables listening for changes to the area where the window cannot be displayed. **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)); +windowClass.on('avoidAreaChange', (data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. type:' + JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area)); }); ``` @@ -1925,7 +2109,8 @@ windowClass.off('keyboardHeightChange'); 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1949,7 +2134,8 @@ windowClass.on('touchOutside', () => { 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1966,6 +2152,209 @@ This is a system API and cannot be called by third-party applications. windowClass.off('touchOutside'); ``` +### on('screenshot')9+ + +on(type: 'screenshot', callback: Callback<void>): void + +Subscribes to screenshot events. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| +| callback | Callback<void> | Yes | Callback invoked when a screenshot event occurs. | + +**Example** + +```js +windowClass.on('screenshot', () => { + console.info('screenshot happened'); +}); +``` + +### off('screenshot')9+ + +off(type: 'screenshot', callback?: Callback<void>): void + +Unsubscribes from screenshot events. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| +| callback | Callback<void> | No | Callback invoked when a screenshot event occurs.| + +**Example** + +```js +var callback = ()=>{ + console.info('screenshot happened'); +} +windowClass.on('screenshot', callback) +windowClass.off('screenshot', callback) + +// If multiple callbacks are enabled in on(), they will all be disabled. +windowClass.off('screenshot'); +``` + +### on('dialogTargetTouch')9+ + +on(type: 'dialogTargetTouch', callback: Callback<void>): void + +Subscribes to click events of the target window in the modal window mode. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| +| callback | Callback<void>| Yes | Callback invoked when the click event occurs in the target window of the modal window mode.| + +**Example** + +```js +windowClass.on('dialogTargetTouch', () => { + console.info('touch dialog target'); +}); +``` + +### off('dialogTargetTouch')9+ + +off(type: 'dialogTargetTouch', callback?: Callback<void>): void + +Unsubscribes from click events of the target window in the modal window mode. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| +| callback | Callback<void> | No | Callback invoked when the click event occurs in the target window of the modal window mode.| + +**Example** + +```js +windowClass.off('dialogTargetTouch'); +``` + +### bindDialogTarget9+ + +bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback<void>, callback: AsyncCallback<void>): void + +Binds the modal window to the target window, and adds a callback to listen for modal window destruction events. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| token | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes | Token of the target window.| +| deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } +} +class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } +} +let token = new TestRemoteObject("testObject"); +windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); +}, (err, data) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); +}); +``` + +### bindDialogTarget9+ + +bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback<void>): Promise<void> + +Binds the modal window to the target window, and adds a callback to listen for modal window destruction events. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| token | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes | Token of the target window.| +| deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } +} +class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } +} +let token = new TestRemoteObject("testObject"); +let promise = windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); +}); +promise.then((data)=> { + console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); +}); +``` + ### isSupportWideGamut8+ isSupportWideGamut(callback: AsyncCallback<boolean>): void @@ -2138,7 +2527,7 @@ 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`.| +| color | string | Yes | Background color to set. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -2166,7 +2555,7 @@ 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 and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| **Return value** @@ -2186,26 +2575,49 @@ promise.then((data)=> { }); ``` -### setBrightness +### setWakeUpScreen()9+ -setBrightness(brightness: number, callback: AsyncCallback<void>): void +setWakeUpScreen(wakeUp: boolean): void; -Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +Wakes up the screen. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| 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 result. | +| Name | Type | Mandatory| Description | +| ---------------- | ------- | ---- | ---------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen.| **Example** ```js -var brightness = 1; -windowClass.setBrightness(brightness, (err, data) => { +var wakeUp = true; +windowClass.setWakeUpScreen(wakeUp); +``` + +### setBrightness + +setBrightness(brightness: number, callback: AsyncCallback<void>): void + +Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| 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 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; @@ -2253,8 +2665,10 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2284,8 +2698,10 @@ setDimBehind(dimBehindValue: number): Promise<void> Sets the dimness of the window that is not on top. This API uses a promise to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2428,7 +2844,7 @@ 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)); + console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); }); ``` @@ -2439,8 +2855,10 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): vo Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2470,8 +2888,10 @@ setOutsideTouchable(touchable: boolean): Promise<void> Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2502,7 +2922,7 @@ promise.then((data)=> { setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void -Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. +Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2531,7 +2951,7 @@ windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { setPrivacyMode(isPrivacyMode: boolean): Promise<void> -Sets whether this window is in privacy mode. This API uses a promise to return the result. +Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2559,6 +2979,25 @@ promise.then((data)=> { }); ``` +### setSnapshotSkip9+ +setSnapshotSkip(isSkip: boolean): void + +Sets whether to ignore this window during screen capturing or recording. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------- | ---- | -------------------- | +| isSkip | boolean | Yes | Whether to ignore the window. The default value is `false`.
The value `true` means that the window is ignored, and `false` means the opposite.
| +```js +var isSkip = true; +windowClass.setSnapshotSkip(isSkip); +``` + ### setTouchable7+ setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void @@ -2626,7 +3065,7 @@ setForbidSplitMove(isForbidSplitMove: boolean, callback: AsyncCallback<void&g 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2657,7 +3096,7 @@ 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 API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2685,11 +3124,330 @@ promise.then((data)=> { }); ``` +### snapshot9+ + +snapshot(callback: AsyncCallback<image.PixelMap>): void + +Captures this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | + +**Example** + +```js +windowClass.snapshot((err, data) => { + if (err.code) { + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + data.release(); // Release the memory in time after the PixelMap is used. +}); +``` + +### snapshot9+ + +snapshot(): Promise<image.PixelMap> + +Captures this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot.| + +**Example** + +```js +let promise = windowClass.snapshot(); +promise.then((pixelMap)=> { + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}).catch((err)=>{ + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); +}); +``` + +### setBlur9+ + +setBlur(radius: number): void + +Blurs this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the window.| + +**Example** + +```js +windowClass.setBlur(4.0); +``` + +### setBackdropBlur9+ + +setBackdropBlur(radius: number): void + +Blurs the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the background of the window.| + +**Example** + +```js +windowClass.setBackdropBlur(4.0); +``` + +### setBackdropBlurStyle9+ + +setBackdropBlurStyle(blurStyle: BlurStyle): void + +Sets the blur style for the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------- | ---- | ---------------------- | +| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window.| + +**Example** + +```js +windowClass.setBackdropBlurStyle(window.BlurType.THIN); +``` + +### setShadow9+ + +setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void + +Sets the shadow for the window borders. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur for the borders. The value is greater than or equal to 0. The value `0` means that the shadow is disabled for the window borders.| +| color | string | No | Color of the shadow. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | +| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | + +**Example** + +```js +windowClass.setShadow(4.0, '#FF00FF00', 2, 3); +``` + +### setCornerRadius9+ + +setCornerRadius(cornerRadius: number): void + +Sets the radius of the rounded corners for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | -------------------- | +| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value `0` means that the window does not use rounded corners.| + +**Example** + +```js +windowClass.setCornerRadius(4.0); +``` + +### opacity9+ + +opacity(opacity: number): void + +Sets the opacity for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------- | +| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0.| + +**Example** + +```js +windowClass.opacity(0.5); +``` + +### scale9+ + +scale(scaleOptions: ScaleOptions): void + +Sets the scale parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------ | ---- | ---------- | +| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set.| + +**Example** + +```js +var obj : window.ScaleOptions; +obj.x = 2.0; +obj.y = 1.0; +obj.pivotX = 0.5; +obj.pivotY = 0.5; +windowClass.scale(obj); +``` + +### rotate9+ + +rotate(rotateOptions: RotateOptions): void + +Sets the rotation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------------- | ---- | ---------- | +| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set.| + +**Example** + +```js +var obj : window.RotateOptions; +obj.x = 1.0; +obj.y = 1.0; +obj.z = 45.0; +obj.pivotX = 0.5; +obj.pivotY = 0.5; +windowClass.rotate(obj); +``` + +### translate9+ + +translate(translateOptions: TranslateOptions): void + +Sets the translation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------- | ---- | ---------- | +| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters to set.| + +**Example** + +```js +var obj : window.TranslateOptions; +obj.x = 100.0; +obj.y = 0.0; +obj.z = 0.0; +windowClass.translate(obj); +``` + +### getTransitionController9+ + + getTransitionController(): TransitionController + +Obtains the transition animation controller. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------- | ---------------- | +| [TransitionController](#transitioncontroller9) | Transition animation controller.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); // Obtain the transition animation controller. +controller.animationForHidden = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); // Set the transition animation. + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +windowClass.showWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}) +``` + ## WindowStageEventType9+ Describes the lifecycle of a window stage. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2712,7 +3470,7 @@ 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2747,7 +3505,7 @@ 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2781,7 +3539,7 @@ createSubWindow(name: string, callback: AsyncCallback<Window>): void 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2818,7 +3576,7 @@ 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2858,7 +3616,7 @@ getSubWindow(callback: AsyncCallback<Array<Window>>): void 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2893,7 +3651,7 @@ 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2927,7 +3685,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<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. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2936,7 +3694,7 @@ This API can be used only in the stage model. | 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.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | 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** @@ -2944,7 +3702,7 @@ This API can be used only in the stage model. ```ts import Ability from '@ohos.application.Ability'; class myAbility extends Ability { - storage : LocalStorage + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -2966,7 +3724,7 @@ 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2975,7 +3733,7 @@ This API can be used only in the stage model. | 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.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** @@ -2988,7 +3746,7 @@ This API can be used only in the stage model. ```ts import Ability from '@ohos.application.Ability'; class myAbility extends Ability { - storage : LocalStorage + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -3011,7 +3769,7 @@ loadContent(path: string, callback: AsyncCallback<void>): void 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. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3046,7 +3804,7 @@ on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType> Enables listening for window stage lifecycle changes. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3077,7 +3835,7 @@ off(eventType: 'windowStageEvent', callback?: Callback<WindowStageEventType&g Disables listening for window stage lifecycle changes. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3106,9 +3864,9 @@ disableWindowDecor(): void Disables window decorators. -This type can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3130,7 +3888,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 API**: This is a system API. + +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3151,3 +3911,145 @@ class myAbility extends Ability { } } ``` +## TransitionContext9+ + +Provides the context for the transition animation. + +**System API**: This is a system API. + +### toWindow9+ + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Readable| Writable| Description | +| -------- | ----------------- | ---- | ---- | ---------------- | +| toWindow | [Window](#window) | Yes | Yes | Target window to display the animation.| + +### completeTransition9+ + +completeTransition(isCompleted: boolean): void + +Completes the transition. This API must be called after [animateTo()](../arkui-ts/ts-explicit-animation.md) is executed. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | ------------------------------------------------------------ | +| isCompleted | boolean | Yes | Whether the transition is complete. The value `true` means that the transition is complete, and `false` means the opposite.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); +controller.animationForShown = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +``` + +## TransitionController9+ + +Implements the transition animation controller. + +**System API**: This is a system API. + +### animationForShown9+ + +animationForShown(context: TransitionContext): void + +Customizes the animation when the window is shown. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); +controller.animationForShown = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +``` + +### animationForHidden9+ + +animationForHidden(context: TransitionContext): void + +Customizes the animation when the window is hidden. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); +controller.animationForHidden = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..a81bb5c76c64a092ea77afb14db231040adf77ac --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -0,0 +1,375 @@ +# Window Animation Management +The **WindowAnimationManager** module provides APIs to listen for application start/exit events and window minimization/maximization events and associate animations with these events. + +> **NOTE** +> +> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + +## Modules to Import + +```js +import windowAnimationManager from '@ohos.animation.windowAnimationManager' +``` + +## windowAnimationManager.setController + +setController(controller: WindowAnimationController): void + +Sets a window animation controller. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| controller | [WindowAnimationController](#windowanimationcontroller) | Yes| Window animation controller to set.| + +**Example** + +```js +var controller = { + onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromLauncher', startingWindowTarget); + }, + onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromRecent', startingWindowTarget); + }, + onStartAppFromOther(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromOther', startingWindowTarget); + }, + onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + }, + onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + }, + onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + }, + onScreenUnlock(finishCallback: WindowAnimationFinishedCallback): void { + } +} + +windowAnimationManager.setController(controller) +``` + +## windowAnimationManager.minimizeWindowWithAnimation + +minimizeWindowWithAnimation(windowTarget: WindowAnimationTarget, callback: AsyncCallback<WindowAnimationFinishedCallback>): void + +Minimizes the window that displays the animation. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes| Target window to minimize.| +| callback | AsyncCallback<[WindowAnimationFinishedCallback](#windowanimationfinishedcallback)> | Yes| Callback invoked when the animation is finished.| + +**Example** + +```js +var target: WindowAnimationTarget = undefined; +var controller = { + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { + target = fullScreenWindowTarget; + }, +} + +windowAnimationManager.setController(controller) + +var finishedCallback = null; +windowAnimationManager.minimizeWindowWithAnimation(target, (err, data) => { + if (err.code) { + console.error('Failed to minimize the window target. Cause: ' + JSON.stringify(err)); + return; + } + + finishedCallback = data; +}); + +finishedCallback.onAnimationFinish(); +``` + +## windowAnimationManager.minimizeWindowWithAnimation + +minimizeWindowWithAnimation(windowTarget: WindowAnimationTarget): Promise<WindowAnimationFinishedCallback> + +Minimizes the window that displays the animation. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes| Target window to display the animation.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[WindowAnimationFinishedCallback](#windowanimationfinishedcallback)> | Promise used to return a call when the animation is finished.| + + +**Example** + +```js +var target: WindowAnimationTarget = undefined; +var controller = { + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { + target = fullScreenWindowTarget; + }, +} + +windowAnimationManager.setController(controller) + +let promise = windowAnimationManager.minimizeWindowWithAnimation(target); +promise.then((data) => { + data.onAnimationFinish(); +}).catch((err)=>{ + console.error('Failed to minimize the window target. Cause: ' + JSON.stringify(err)); + return; +}); +``` + +## WindowAnimationController + +Implements the window animation controller. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +### onStartAppFromLauncher + +onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when an application is started from the home screen. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------ | +| startingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromLauncher', startingWindowTarget); + } +} +``` + +### onStartAppFromRecent + +onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget,finishCallback:WindowAnimationFinishedCallback): void + +Called when an application is started from the recent task list. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------ | +| startingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromRecent', startingWindowTarget); + } +} +``` + +### onStartAppFromOther + +onStartAppFromOther(startingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when an application is started from a place other than the home screen and recent task list. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------ | +| startingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onStartAppFromOther(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromOther', startingWindowTarget); + } +} +``` + +### onAppTransition + +onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called during application transition. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| fromWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Window that displays the animation before the transition.| +| toWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Window that displays the animation after the transition.| +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, + finishCallback: WindowAnimationFinishedCallback): void { + console.log('onAppTransition', fromWindowTarget); + } +} +``` + +### onMinimizeWindow + +onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when a window is minimized. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| minimizingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onMinimizeWindow', minimizingWindowTarget); + } +} +``` + +### onCloseWindow + +onCloseWindow(closingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when a window is closed. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| closingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onCloseWindow', closingWindowTarget); + } +} +``` + +### onScreenUnlock + +onScreenUnlock(finishCallback: [WindowAnimationFinishedCallback](#windowanimationfinishedcallback)): void + +Called when the screen is unlocked. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------------------------------ | ---- | ------------------ | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onScreenUnlock(finishCallback: WindowAnimationFinishedCallback): void { + console.log('onScreenUnlock'.); + } +} +``` + +### onWindowAnimationTargetsUpdate + +onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array<WindowAnimationTarget>): void + +Called when the window that displays the animation is updated. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| fullScreenWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window in full-screen mode.| +| floatingWindowTargets| Array<[WindowAnimationTarget](#windowanimationtarget)> | Yes | Target window in the form of a floating window.| + +**Example** + +```js +var controller = { + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { + console.log('onWindowAnimationTargetsUpdate'.); + } +} + +windowAnimationManager.setController(controller) +``` + +## WindowAnimationFinishedCallback +Implements a callback that is invoked when the animation is finished. + +### onAnimationFinish + +onAnimationFinish():void + +Called when the animation is finished. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Example** + +```js +var controller = { + onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + finishCallback.onAnimationFinish(); + } +} +``` + +## WindowAnimationTarget +Implements animation in a window. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Description| +| ------- | ------ | ----------------------- | +| bundleName | string | Bundle name corresponding to the target window.| +| abilityName | string | Ability name corresponding to the target window.| +| windowBounds | [RRect](#rrect) | Actual size of the target window.| +| missionId | number | Mission ID.| + +## RRect +Describes a rounded rectangle. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Description| +| ------- | ------ | ----------------------- | +| left | number | Horizontal coordinate of the upper left corner of the target window relative to the screen.| +| top | number | Vertical coordinate of the upper left corner of the target window relative to the screen.| +| width | number | Width of the target window.| +| height | number | Height of the target window.| +| radius | number | Radius of the rounded corner of the target window.| diff --git a/en/application-dev/task-management/background-task-dev-guide.md b/en/application-dev/task-management/background-task-dev-guide.md index e8d85cc571320bd7994e9e80a9b72e89acff367b..e820da263fb189ab9a2717c45a31a82d830a8cbc 100644 --- a/en/application-dev/task-management/background-task-dev-guide.md +++ b/en/application-dev/task-management/background-task-dev-guide.md @@ -10,11 +10,11 @@ If a service needs to be continued when the application or service module is run **Table 1** Main APIs for transient tasks -| API| Description| -| -------- | -------- | -| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.
The default duration value of delayed suspension is 180000 when the battery level is normal and 60000 when the battery level is low.| -| getRemainingDelayTime(requestId: number): Promise<number> | Obtains the remaining duration before the application is suspended.
This API uses a promise to return the task execution result.| -| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay.| +| API | Description | +| ---------------------------------------- | ---------------------------------------- | +| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.
The default duration value of delayed suspension is 180000 when the battery level is normal and 60000 when the battery level is low.| +| getRemainingDelayTime(requestId: number): Promise<number> | Obtains the remaining duration before the application is suspended.
This API uses a promise to return the result. | +| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. | ### How to Develop @@ -24,12 +24,12 @@ If a service needs to be continued when the application or service module is run ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; - + let myReason = 'test requestSuspendDelay'; let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { console.info("Request suspension delay will time out."); }); - + var id = delayInfo.requestId; console.info("requestId is: " + id); ``` @@ -91,31 +91,33 @@ ohos.permission.KEEP_BACKGROUND_RUNNING **Table 2** Main APIs for continuous tasks -| API| Description| -| -------- | -------- | +| API | Description | +| ---------------------------------------- | ---------------------------- | | startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> | Requests a continuous task from the system so that the application keeps running in the background.| -| stopBackgroundRunning(context: Context): Promise<void> | Cancels the continuous task.| +| stopBackgroundRunning(context: Context): Promise<void> | Cancels the continuous task. | For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md). **Table 3** Background modes -| Name| ID| Description| Item| -| -------- | -------- | -------- | -------- | -| DATA_TRANSFER | 1 | Data transfer.| dataTransfer | -| AUDIO_PLAYBACK | 2 | Audio playback.| audioPlayback | -| AUDIO_RECORDING | 3 | Audio recording.| audioRecording | -| LOCATION | 4 | Positioning and navigation.| location | -| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task.| bluetoothInteraction | -| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.| multiDeviceConnection | -| WIFI_INTERACTION | 7 | WLAN-related task (reserved).| wifiInteraction | -| VOIP | 8 | Voice and video call (reserved).| voip | -| TASK_KEEPING | 9 | Computing task (for specific devices only).| taskKeeping | +| Name | ID | Description | Configuration Item | +| ----------------------- | ---- | -------------- | --------------------- | +| DATA_TRANSFER | 1 | Data transfer. | dataTransfer | +| AUDIO_PLAYBACK | 2 | Audio playback. | audioPlayback | +| AUDIO_RECORDING | 3 | Audio recording. | audioRecording | +| LOCATION | 4 | Positioning and navigation. | location | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | bluetoothInteraction | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | multiDeviceConnection | +| WIFI_INTERACTION | 7 | WLAN-related task (reserved). | wifiInteraction | +| VOIP | 8 | Voice and video call (reserved). | voip | +| TASK_KEEPING | 9 | Computing task (for specific devices only).| taskKeeping | ### How to Develop +Development on the FA model: + 1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission and background mode type in the **config.json** file, with the ability type set to **service**. ``` @@ -137,7 +139,7 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA ] } ``` - + 2. Request a continuous task. ```js @@ -173,16 +175,84 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; - + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { console.info("Operation stopBackgroundRunning succeeded"); }).catch((err) => { console.error("Operation stopBackgroundRunning failed Cause: " + err); }); - + + ``` + +Development on the stage model: + +1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission and background mode type in the **module.json5** file. + + ``` + "module": { + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // Background mode + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission + } + ] + } ``` +2. Request a continuous task. + + ```ts + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + }); + ``` + +3. Cancel the continuous task. + + ```ts + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + + ``` + + ### Development Examples + +Development on the FA model: + For details about how to use the Service ability in the FA model, see [Service Ability Development](../ability/fa-serviceability.md). If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources. @@ -284,3 +354,127 @@ export default { } }; ``` + +Development on the stage model: + +For details about the stage model, see [Stage Model Overview](../ability/stage-brief.md). +If an application needs to run a continuous task in the background, you can use **Call** to create and run an ability in the background. For details, see [Call Development](../ability/stage-call.md). + +```ts +import Ability from '@ohos.application.Ability' +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import wantAgent from '@ohos.wantAgent'; + +let mContext = null; + +function startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + // Type of the operation to perform after the notification is clicked. + operationType: wantAgent.OperationType.START_ABILITY, + // Custom request code. + requestCode: 0, + // Execution attribute of the operation to perform after the notification is clicked. + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(mContext, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + }); +} + +function stopContinuousTask() { + backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); +} + +class MySequenceable { + num: number = 0; + str: String = ""; + + constructor(num, string) { + this.num = num; + this.str = string; + } + + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } +} + +function sendMsgCallback(data) { + console.info('BgTaskAbility funcCallBack is called ' + data) + let receivedData = new Mysequenceable(0, "") + data.readSequenceable(receivedData) + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) + if (receivedData.str === 'start_bgtask') { + startContinuousTask() + } else if (receivedData.str === 'stop_bgtask') { + stopContinuousTask(); + } + return new Mysequenceable(10, "Callee test"); +} + +export default class BgTaskAbility extends Ability { + onCreate(want, launchParam) { + console.info("[Demo] BgTaskAbility onCreate") + this.callee.on("test", sendMsgCallback); + + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + mContext = this.context; + } + + onDestroy() { + console.info("[Demo] BgTaskAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + console.info("[Demo] BgTaskAbility onWindowStageCreate") + + windowStage.loadContent("pages/second").then((data)=> { + console.info(`load content succeed with data ${JSON.stringify(data)}`) + }).catch((error)=>{ + console.error(`load content failed with error ${JSON.stringify(error)}`) + }) + } + + onWindowStageDestroy() { + console.info("[Demo] BgTaskAbility onWindowStageDestroy") + } + + onForeground() { + console.info("[Demo] BgTaskAbility onForeground") + } + + onBackground() { + console.info("[Demo] BgTaskAbility onBackground") + } +}; +``` diff --git a/en/device-dev/driver/driver-peripherals-vibrator-des.md b/en/device-dev/driver/driver-peripherals-vibrator-des.md index c4603f7d46e5ac0375ed9aabc8a3a967c64fbafa..6a6164eef36695838ee3bfb9a0590c7e727d2b42 100644 --- a/en/device-dev/driver/driver-peripherals-vibrator-des.md +++ b/en/device-dev/driver/driver-peripherals-vibrator-des.md @@ -4,7 +4,7 @@ ### Introduction -Developed on the Hardware Driver Foundation (HDF), the vibrator driver model makes vibrator driver development easier. This model masks the interaction between the device driver and system, provides unified and stable driver interfaces for the hardware service layer, and offers open interfaces and interface parsing capabilities for driver developers. This document provides guidance for developing vibrator drivers and deploying vibrators in different OSs. The figure below shows the vibrator driver model. +Developed on the Hardware Driver Foundation (HDF), the vibrator driver model makes vibrator driver development easier. The motor driver model shields the interaction between the device driver and the system and provides unified and stable driver interface capabilities for the hardware service layer. It also provides open interfaces and interface parsing capabilities for developers to develop vibrator drivers and deploy vibrators in different OSs.
The figure below shows the vibrator driver model. **Figure 1** Vibrator driver model @@ -20,22 +20,22 @@ The system controls device vibration by invoking the vibrator. There are two vib - Periodic vibration - The vibrator vibrates with a preset effect. For example, if the preset effect is "haptic.clock.timer" = [600, 600, 200, 600], the vibrator waits for 600 ms, vibrates for 600 ms, waits for 200 ms, and vibrates for 600 ms. + The vibrator vibrates with a preset effect. For example, if **haptic.clock.timer** is set to **[600, 600, 200, 600]**, the vibrator waits for 600 ms, vibrates for 600 ms, waits for 200 ms, and vibrates for 600 ms. ### Working Principles -Based on the loading and running process (shown below) of the vibrator driver model, the relationships between key modules in the model and associated modules are clearly defined. +The figure below shows how a vibrator driver is loaded. -**Figure 2** How vibrator driver works +**Figure 2** How a vibrator driver works ![How vibrator driver works](figures/vibrator_working.png) The following uses the vibrator driver on the Hi3516D V300 development board of the standard system as an example to describe the driver loading and running process. -1. The vibrator host reads the vibrator management configuration from the Vibrator Host node of the device_info HCS (vibrator device information HCS). -2. The vibrator host parses the vibrator management configuration and associates it with the corresponding vibrator abstract driver. -3. The vibrator host reads the vibrator data configuration from the linear_vibrator_config HCS (vibrator private configuration HCS). -4. The vibrator host parses the vibrator data configuration and associates it with the corresponding vibrator haptic driver. +1. The vibrator driver reads the vibrator management configuration information from **Vibrator Host** in the **device_info.hcs** file. +2. The HCS parser parses the vibrator management configuration and associates it with the vibrator abstract driver. +3. The vibrator chipset driver reads the vibrator data configuration from the **linear_vibrator_config.hcs** file. +4. The HCS parser parses the vibrator data configuration and associates it with the vibrator haptic driver. 5. The vibrator proxy delivers an instruction to the vibrator stub. 6. The vibrator stub calls the vibrator controller. 7. The vibrator host initializes the vibrator abstract driver interfaces. @@ -51,32 +51,34 @@ You can set different vibration effects as needed, for example, customizing vibr ### Available APIs -The vibrator driver model supports static HDF Configuration Source (HCS) configurations and dynamic parameter configurations. The vibrator hardware service calls the **StartOnce** interface to trigger continuous vibration and calls the **Start** interface to trigger vibration with a specified effect. The table below lists the APIs provided by the vibrator driver model for the hardware service layer. +The vibrator driver model supports static HDF Configuration Source (HCS) configuration and dynamic parameter configuration. The vibrator hardware service calls **StartOnce()** to trigger continuous vibration and calls **Start()** to trigger vibration with a specified effect. The table below lists the APIs provided by the vibrator driver model for the hardware service layer. -**Table 1** External APIs of the vibrator driver model +**Table 1** APIs of the vibrator driver model -| API | Description | -| -------------------------------------- | -------------------------------------------------------- | -| int32_t StartOnce(uint32_t duration) | Triggers vibration with a given **duration**. | -| int32_t Start(const char *effectType) | Triggers vibration with a given effect, which is specified by **effectType**.| -| int32_t Stop(enum VibratorMode mode) | Stops vibration. | +| API | Description | +| -------------------------------------- | ------------------------------------------------ | +| int32_t StartOnce(uint32_t duration) | Triggers vibration with a given **duration**. | +| int32_t Start(const char *effectType) | Triggers vibration with a given effect, which is specified by **effectType**. | +| int32_t Stop(enum VibratorMode mode) | Stops vibration. | +| int32_t EnableVibratorModulation(uint32_t duration, int32_t intensity, int32_t frequency) | Triggers vibration with the given **duration**, **frequency**, and **intensity**.| +| int32_t GetVibratorInfo(struct VibratorInfo **vibratorInfo); | Obtains vibrator information, including whether the intensity and frequency can be set and the intensity and frequency range.| ### How to Develop -The vibrator driver model provides stable interfaces for the upper-layer hardware service to trigger a one-shot vibration with a given duration, trigger vibration with a given effect, and stop vibration. The model implements functionalities such as cross-OS migration and differentiated configurations. To develop a vibrator, perform the following steps: +The vibrator driver model provides APIs for the upper-layer hardware service to trigger a one-shot vibration with a given duration, trigger vibration with a given effect, and stop vibration. This model implements functionalities such as cross-OS porting and device-specific configurations. The development procedure is as follows: -1. Develop the vibrator abstract driver based on the driver entry. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions, configure resources, and parse HCS configurations. +1. Develop the vibrator abstract driver based on the driver entry. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions, configure resources, and parse the HCS. - - Call **HDF_INIT** to register the driver entry with the HDF. During driver loading, the HDF calls the **Bind** function and then the **Init** function to load the driver. If the **Init** function fails to be called, the HDF calls **Release** to release the driver resources and exit the vibrator driver model. The vibrator driver model uses the HCS as the configuration source code. For details about HCS fields, see [Driver Configuration Management](driver-hdf-manage.md). The driver entry function is defined as follows: + - Call **HDF_INIT** to register the driver entry with the HDF. During driver loading, the HDF calls the **Bind** function and then the **Init** function to load the driver. If the **Init** function fails to be called, the HDF calls **Release** to release the driver resources and exit the vibrator driver model. The vibrator driver model uses the HCS as the configuration source code. For details about HCS configuration fields, see [Configuration Management](driver-hdf-manage.md). The driver entry function is defined as follows: ```c /* Register the entry structure object of the vibrator abstract driver. */ struct HdfDriverEntry g_vibratorDriverEntry = { .moduleVersion = 1, // Version of the vibrator module. - .moduleName = "HDF_VIBRATOR", // Vibrator module name. The value must be the same as the value of moduleName in the device_info.hcs file. + .moduleName = "HDF_VIBRATOR", // Vibrator module name, which must be the same as moduleName in the device_info.hcs file. .Bind = BindVibratorDriver, // Function for binding a vibrator. .Init = InitVibratorDriver, // Function for initializing a vibrator. - .Release = ReleaseVibratorDriver, // Function for releasing vibrator resources. + .Release = ReleaseVibratorDriver, // Function for releasing vibrator resources. }; HDF_INIT(g_vibratorDriverEntry); @@ -85,18 +87,18 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar - Develop the vibrator abstract driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. ```c - /* External service published by the vibrator driver. */ + /* Message exchange capability of the vibrator driver. */ static int32_t DispatchVibrator(struct HdfDeviceIoClient *client, int32_t cmd, struct HdfSBuf *data, struct HdfSBuf *reply) { int32_t loop; - + for (loop = 0; loop < sizeof(g_vibratorCmdHandle) / sizeof(g_vibratorCmdHandle[0]); ++loop) { if ((cmd == g_vibratorCmdHandle[loop].cmd) && (g_vibratorCmdHandle[loop].func != NULL)) { return g_vibratorCmdHandle[loop].func(data, reply); } } - + return HDF_SUCCESS; } @@ -105,34 +107,34 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar { struct VibratorDriverData *drvData = NULL; CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(device, HDF_FAILURE); - + drvData = (struct VibratorDriverData *)OsalMemCalloc(sizeof(*drvData)); CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_MALLOC_FAIL); - + drvData->ioService.Dispatch = DispatchVibrator; drvData->device = device; device->service = &drvData->ioService; g_vibratorDrvData = drvData; - + return HDF_SUCCESS; } - + /* Entry function for vibrator driver initialization. */ int32_t InitVibratorDriver(struct HdfDeviceObject *device) { struct VibratorDriverData *drvData = NULL; - + drvData->mode = VIBRATOR_MODE_BUTT; drvData->state = VIBRATOR_STATE_IDLE; ...... if (CreateVibratorHaptic(device) != HDF_SUCCESS) { - HDF_LOGE("%s: init workQueue fail!", __func__); + HDF_LOGE("%s: init workQueue failed!", __func__); return HDF_FAILURE; } - + return HDF_SUCCESS; } - + /* Release the resources allocated during vibrator driver initialization. */ void ReleaseVibratorDriver(struct HdfDeviceObject *device) { @@ -155,21 +157,21 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar device0 :: deviceNode { policy = 2; // Policy for publishing the driver service. priority = 100; // Driver startup priority (0–200). A larger value indicates a lower priority. The default value 100 is recommended. The sequence for loading devices with the same priority is random. - preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite. + preload = 0; // Whether to load the driver on demand. The value 0 means to load the driver on demand, and 2 means the opposite. permission = 0664; // Permission for the driver to create a device node. - moduleName = "HDF_VIBRATOR"; // Driver name. The value must be the same as that of moduleName in the driver entry structure. + moduleName = "HDF_VIBRATOR"; // Driver name, which must be the same as moduleName in the driver entry structure. serviceName = "hdf_misc_vibrator"; // Name of the service provided by the driver. The name must be unique. deviceMatchAttr = "hdf_vibrator_driver"; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. } } ``` -2. Create a vibrator haptic model and parse the haptic HCS configuration. +2. Create a vibrator haptic model and parse the haptic HCS. - Create a vibrator haptic model. - ```hcs - /* Create a vibrator haptic model, allocate resources, and parse the haptic HCS configuration. */ + ```c + /* Create a vibrator haptic model, allocate resources, and parse the haptic HCS. */ int32_t CreateVibratorHaptic(struct HdfDeviceObject *device) { struct VibratorHapticData *hapticData = NULL; @@ -181,15 +183,15 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar hapticData->supportHaptic = false; if (OsalMutexInit(&hapticData->mutex) != HDF_SUCCESS) { - HDF_LOGE("%s: fail to init mutex", __func__); + HDF_LOGE("%s: failed to init mutex", __func__); goto EXIT; } DListHeadInit(&hapticData->effectSeqHead); - /* Parse the haptic HCS configuration. */ + /* Parse the haptic HCS. */ if (ParserVibratorHapticConfig(device->property) != HDF_SUCCESS) { - HDF_LOGE("%s: parser haptic config fail!", __func__); + HDF_LOGE("%s: parser haptic config failed!", __func__); goto EXIT; } @@ -200,9 +202,9 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar } ``` - - The vibrator effect model uses the HCS. For details about HCS fields, see [Driver Configuration Management](driver-hdf-manage.md). + - The vibrator haptic model uses the HCS. For details about the HCS fields, see [Configuration Management](driver-hdf-manage.md). - ``` + ```hcs /* Vibrator data configuration template (vibrator_config.hcs). */ root { vibratorConfig { @@ -250,7 +252,7 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar /* Create a timer based on the vibration effect. */ ret = StartHaptic(&config); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: start haptic fail!", __func__); + HDF_LOGE("%s: start haptic failed!", __func__); return ret; } @@ -272,7 +274,7 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar ret = StartHaptic(&config); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: start haptic fail!", __func__); + HDF_LOGE("%s: start haptic failed!", __func__); return ret; } @@ -290,7 +292,7 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar /* Stop vibration and destroy the timer. */ ret = StopHaptic(); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: stop haptic fail!", __func__); + HDF_LOGE("%s: stop haptic failed!", __func__); return ret; } @@ -300,6 +302,58 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar return HDF_SUCCESS; } + + /* Trigger vibration with the given duration, frequency, and intensity. */ + static int32_t EnableModulationParameter(struct HdfSBuf *data, struct HdfSBuf *reply) + { + (void)reply; + struct VibratorEffectCfg config; + struct VibratorDriverData *drvData; + uint32_t duration; + int32_t intensity; + int32_t frequency; + int32_t ret; + ..... + (void)OsalMutexLock(&drvData->mutex); + drvData->mode = VIBRATOR_MODE_ONCE; + (void)OsalMutexUnlock(&drvData->mutex); + /* Set the vibration intensity and frequency. */ + ret = drvData->ops.SetParameter(intensity, frequency); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: set parameter failed", __func__); + return HDF_FAILURE; + } + + config.cfgMode = VIBRATOR_MODE_ONCE; + config.duration = duration; + config.effect = NULL; + + ret = StartHaptic(&config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: start haptic failed", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } + + /* Obtain vibrator information, including whether the intensity and frequency can be set and the intensity and frequency range. */ + static int32_t GetVibratorInfo(struct HdfSBuf *data, struct HdfSBuf *reply) + { + (void)data; + struct VibratorDriverData *drvData; + + drvData = GetVibratorDrvData(); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(reply, HDF_ERR_INVALID_PARAM); + + if (!HdfSbufWriteBuffer(reply, &drvData->vibratorInfo, sizeof(drvData->vibratorInfo))) { + HDF_LOGE("%s: write sbuf failed", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } ``` 4. Implement the interfaces for the vibrator chipset driver. @@ -319,50 +373,180 @@ The vibrator driver model provides stable interfaces for the upper-layer hardwar drvData->ops.Start = ops->Start; drvData->ops.StartEffect = ops->StartEffect; drvData->ops.Stop = ops->Stop; + drvData->ops.SetParameter = ops->SetParameter; + (void)OsalMutexUnlock(&drvData->mutex); + + return HDF_SUCCESS; + } + + /* Register vibrator information. */ + int32_t RegisterVibratorInfo(struct VibratorInfo *vibratorInfo) + { + struct VibratorDriverData *drvData = GetVibratorDrvData(); + + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(vibratorInfo, HDF_FAILURE); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + + (void)OsalMutexLock(&drvData->mutex); + if (memcpy_s(&drvData->vibratorInfo, sizeof(drvData->vibratorInfo), vibratorInfo, sizeof(*vibratorInfo)) != EOK) { + HDF_LOGE("%s: Memcpy vibrator config failed", __func__); + return HDF_FAILURE; + } (void)OsalMutexUnlock(&drvData->mutex); return HDF_SUCCESS; } ``` + + - The vibrator driver model provides vibrator chipset driver interfaces. Implement these interfaces as follows: ```c - /* Start a linear vibrator to vibrate with a given duration. */ - static int32_t StartLinearVibrator() + /* Stop vibration based on the specified vibration mode. */ + static int32_t StopModulationParameter() { - int32_t ret; - struct VibratorLinearDriverData *drvData = GetLinearVibratorData(); - CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); - ...... - ret = GpioWrite(drvData->gpioNum, GPIO_VAL_LOW); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: pull gpio%d to %d level failed", __func__, drvData->gpioNum, GPIO_VAL_LOW); - return ret; + uint8_t value[DRV2605L_VALUE_BUTT]; + struct Drv2605lDriverData *drvData = NULL; + drvData = GetDrv2605lDrvData(); + + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData->drv2605lCfgData, HDF_FAILURE); + + value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_MODE; + value[DRV2605L_VALUE_INDEX] = (uint8_t)DRV2605_MODE_STANDBY; + if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { + HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); + return HDF_FAILURE; + } + + value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_RTPIN; + value[DRV2605L_VALUE_INDEX] = (uint8_t)&drvData->drv2605lCfgData->vibratorAttr.defaultIntensity; + if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { + HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); + } + + value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_LRARESON; + value[DRV2605L_VALUE_INDEX] = (uint8_t)&drvData->drv2605lCfgData->vibratorAttr.defaultFrequency; + if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { + HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); } - return HDF_SUCCESS; - } - /* Start a linear vibration to vibrate with a given effect. */ - static int32_t StartEffectLinearVibrator(uint32_t effectType) - { - (void)effectType; - HDF_LOGE("%s: vibrator set build-in effect no support!", __func__); return HDF_SUCCESS; } - /* Stop a linear vibration based on the specified vibration mode. */ - static int32_t StopLinearVibrator() + /* Set the vibration intensity and frequency. */ + static void SetModulationParameter(int32_t intensity, int32_t frequency) { - int32_t ret; - struct VibratorLinearDriverData *drvData = GetLinearVibratorData(); + uint8_t value[DRV2605L_VALUE_BUTT]; + struct Drv2605lDriverData *drvData = NULL; + drvData = GetDrv2605lDrvData(); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); - ...... - ret = GpioWrite(drvData->gpioNum, GPIO_VAL_HIGH); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: pull gpio%d to %d level failed", __func__, drvData->gpioNum, GPIO_VAL_HIGH); - return ret; + + if (intensity != 0) { + value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_RTPIN; + value[DRV2605L_VALUE_INDEX] = (uint8_t)INTENSITY_MAPPING_VALUE(intensity); + if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { + HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); + return; + } + } else { + HDF_LOGD("%s: the setting of intensity 0 is not supported and \ + will be set as the system default intensity", __func__); + } + + if (frequency != 0) { + value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_LRARESON; + value[DRV2605L_VALUE_INDEX] = (uint8_t)FREQUENCY_MAPPING_VALUE(frequency); + if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { + HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); + return; + } + } else { + HDF_LOGD("%s: the setting of frequency 0 is not supported and \ + will be set as the system default frequency", __func__); } - return HDF_SUCCESS; } ``` + +### Verification + +After the driver is developed, develop test cases in the sensor unit test to verify the basic functions of the driver. Use the developer self-test platform as the test environment. + +``` +/* Initialize the vibrator interface instance before executing test cases. */ +void HdfVibratorTest::SetUpTestCase() +{ + g_vibratorDev = NewVibratorInterfaceInstance(); +} +/* Release test case resources. */ +void HdfVibratorTest::TearDownTestCase() +{ + if(g_vibratorDev != nullptr){ + FreeVibratorInterfaceInstance(); + g_vibratorDev = nullptr; + } +} + +/* Verify one-short vibration. */ +HWTEST_F(HdfVibratorTest, PerformOneShotVibratorDuration_001, TestSize.Level1) +{ + ASSERT_NE(nullptr, g_vibratorDev); + + int32_t startRet = g_vibratorDev->StartOnce(g_duration); + EXPECT_EQ(startRet, HDF_SUCCESS); + + OsalMSleep(g_sleepTime1); + + int32_t endRet = g_vibratorDev->Stop(VIBRATOR_MODE_ONCE); + EXPECT_EQ(endRet, HDF_SUCCESS); +} +/* Verify vibration with the preset effect. */ +HWTEST_F(HdfVibratorTest, ExecuteVibratorEffect_002, TestSize.Level1) +{ + ASSERT_NE(nullptr, g_vibratorDev); + + int32_t startRet = g_vibratorDev->Start(g_builtIn); + EXPECT_EQ(startRet, HDF_SUCCESS); + + OsalMSleep(g_sleepTime1); + + int32_t endRet = g_vibratorDev->Stop(VIBRATOR_MODE_PRESET); + EXPECT_EQ(endRet, HDF_SUCCESS); +} +/* Obtain vibrator information, including whether the intensity and frequency can be set and the intensity and frequency range. */ +HWTEST_F(HdfVibratorTest, GetVibratorInfo_001, TestSize.Level1) +{ + ASSERT_NE(nullptr, g_vibratorDev); + + int32_t startRet = g_vibratorDev->GetVibratorInfo(&g_vibratorInfo); + EXPECT_EQ(startRet, HDF_SUCCESS); + EXPECT_NE(g_vibratorInfo, nullptr); + + printf("intensity = %d, intensityMaxValue = %d, intensityMinValue = %d\n\t", + g_vibratorInfo->isSupportIntensity, g_vibratorInfo->intensityMaxValue, g_vibratorInfo->intensityMinValue); + printf("frequency = %d, frequencyMaxValue = %d, frequencyMinValue = %d\n\t", + g_vibratorInfo->isSupportFrequency, g_vibratorInfo->frequencyMaxValue, g_vibratorInfo->frequencyMinValue); +} +/* Trigger vibration with the given duration, frequency, and intensity. */ +HWTEST_F(HdfVibratorTest, EnableVibratorModulation_001, TestSize.Level1) +{ + int32_t startRet; + ASSERT_NE(nullptr, g_vibratorDev); + EXPECT_GT(g_duration, 0); + + if ((g_vibratorInfo->isSupportIntensity == 1) || (g_vibratorInfo->isSupportFrequency == 1)) { + EXPECT_GE(g_intensity1, g_vibratorInfo->intensityMinValue); + EXPECT_LE(g_intensity1, g_vibratorInfo->intensityMaxValue); + EXPECT_GE(g_frequency1, g_vibratorInfo->frequencyMinValue); + EXPECT_LE(g_frequency1, g_vibratorInfo->frequencyMaxValue); + + startRet = g_vibratorDev->EnableVibratorModulation(g_duration, g_intensity1, g_frequency1); + EXPECT_EQ(startRet, HDF_SUCCESS); + OsalMSleep(g_sleepTime1); + startRet = g_vibratorDev->Stop(VIBRATOR_MODE_ONCE); + EXPECT_EQ(startRet, HDF_SUCCESS); + } +} +``` diff --git a/en/device-dev/porting/porting-chip-board-hal.md b/en/device-dev/porting/porting-chip-board-hal.md index f3bf12e1fee0c2deee2be149464ea3e8586a08f6..d06c425d8c3d6314b8b64111bf15bd2b795b9ad9 100644 --- a/en/device-dev/porting/porting-chip-board-hal.md +++ b/en/device-dev/porting/porting-chip-board-hal.md @@ -20,7 +20,7 @@ The IoT peripheral subsystem provides dedicated peripheral operation interfaces **Description for HAL APIs of the IoT peripheral subsystem** -The SoC needs to implement related APIs. For details about the dependency of OpenHarmony on the chip peripheral APIs, see [HAL header files of IoT peripherals](https://gitee.com/openharmony/iothardware_peripheral/tree/master/interfaces/kits). +The SoC needs to implement related APIs. For details about the dependency of OpenHarmony on the chip peripheral APIs, see [HAL header files of IoT peripherals](https://gitee.com/openharmony/iothardware_peripheral/tree/master/interfaces/inner_api). ## WLAN diff --git a/zh-cn/application-dev/Readme-CN.md b/zh-cn/application-dev/Readme-CN.md index 19b9ca337e53338101d7d995f08865062ed8b290..ae23f2193f7096885e1fd4d7e38f652013b4ca38 100644 --- a/zh-cn/application-dev/Readme-CN.md +++ b/zh-cn/application-dev/Readme-CN.md @@ -43,6 +43,7 @@ - API参考 - [组件参考(基于TS扩展的声明式开发范式)](reference/arkui-ts/Readme-CN.md) - [组件参考(基于JS扩展的类Web开发范式)](reference/arkui-js/Readme-CN.md) + - [JS服务卡片UI组件参考](reference/js-service-widget-ui/Readme-CN.md) - 接口 - [JS及TS API参考](reference/apis/Readme-CN.md) - Native API diff --git a/zh-cn/application-dev/ability/figures/page-ability-lifecycle.png b/zh-cn/application-dev/ability/figures/page-ability-lifecycle.png index edb49acd0647f3af7355ceda987c5ca812866128..b35954967bb9c733725da2f0700481932619ae45 100755 Binary files a/zh-cn/application-dev/ability/figures/page-ability-lifecycle.png and b/zh-cn/application-dev/ability/figures/page-ability-lifecycle.png differ diff --git a/zh-cn/application-dev/ability/figures/stage-call.png b/zh-cn/application-dev/ability/figures/stage-call.png index 28f2a0f7ea9d86fc81e0c1a37d556384b14a9bdd..511632f7b7ce2c4c4d6582792311184f46fbf703 100644 Binary files a/zh-cn/application-dev/ability/figures/stage-call.png and b/zh-cn/application-dev/ability/figures/stage-call.png differ diff --git a/zh-cn/application-dev/ability/stage-call.md b/zh-cn/application-dev/ability/stage-call.md index e8126fa0d7b92f82c9a35d2b92fe3d5017f9ca4d..65f12149bf2c142269eb697baa39962cc65f79c1 100644 --- a/zh-cn/application-dev/ability/stage-call.md +++ b/zh-cn/application-dev/ability/stage-call.md @@ -1,39 +1,58 @@ # Call调用开发指导 ## 场景介绍 -Ability Call调用是Ability能力的扩展,它为Ability提供一种能够被外部调用的能力,使Ability既能被拉起到前台展示UI,也支持Ability在后台被创建并运行。应用开发者可通过Call调用,使用IPC通信实现不同Ability之间的数据共享。Call调用的场景主要包括: -- 创建Callee被调用端。 -- 访问Callee被调用端。 +Call调用是Ability能力的扩展,它为Ability提供一种能够被外部调用并与外部进行通信的能力。Call调用支持前台与后台两种启动方式,使Ability既能被拉起到前台展示UI,也可以在后台被创建并运行。Call调用在调用方与被调用方间建立了IPC通信,因此应用开发者可通过Call调用实现不同Ability之间的数据共享。 + +Call调用的核心接口是startAbilityByCall方法,与startAbility接口的不同之处在于: + - startAbilityByCall支持前台与后台两种启动方式,而startAbility仅支持前台启动。 + - 调用方可使用startAbilityByCall所返回的Caller对象与被调用方进行通信,而startAbilty不具备通信能力。 + +Call调用的使用场景主要包括: +- 需要与被启动的Ability进行通信 +- 希望被启动的Ability在后台运行 -本文中的Caller和Callee分别表示调用者和被调用者,IPC表示进程间通信,Call调用流程示意图如下。 +**表1** Call调用相关名词解释 +|名词|描述| +|:------|:------| +|CallerAbility|指代进行Call调用的Ability(调用方)| +|CalleeAbility|指代被Call调用的Ability(被调用方)| +|Caller |实际对象,由startAbilityByCall接口所返回,CallerAbility可使用Caller与CalleeAbility进行通信,具体接口见表2| +|Callee |实际对象,被Ability对象所持有,可与Caller进行通信| +|IPC |指代进程间通信| +Call调用流程示意图如下: + - CallerAbility调用startAbilityByCall接口获取Caller,并使用Caller对象的call方法向CalleeAbility发送数据 + - CalleeAbility持有一个Callee对象,通过Callee的on方法注册回调函数,当接收到Caller发送的数据时将会调用对应的回调函数 ![stage-call](figures/stage-call.png) > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> Callee被调用端所在的Ability,启动模式需要为单实例。 -> 当前仅支持系统应用及ServiceExtensionAbility使用Call访问Callee。 +> CalleeAbility的启动模式需要为单实例。 +> 当前仅支持系统应用使用Call调用。 ## 接口说明 Caller及Callee功能如下:具体的API详见[接口文档](../reference/apis/js-apis-application-ability.md#caller)。 -**表1** Call API接口功能介绍 +**表2** Call API接口功能介绍 |接口名|描述| |:------|:------| -|startAbilityByCall(want: Want): Promise\|获取指定通用组件的Caller通信接口,拉起指定通用组件并将其切换到后台。| +|startAbilityByCall(want: Want): Promise\|启动指定Ability并获取其Caller通信接口,默认为后台启动,通过配置want可实现前台启动,详见[接口文档](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall)。AbilityContext与ServiceExtensionContext均支持该接口。| |on(method: string, callback: CalleeCallBack): void|通用组件Callee注册method对应的callback方法。| -|off(method: string): void|通用组件Callee去注册method的callback方法。| +|off(method: string): void|通用组件Callee解注册method的callback方法。| |call(method: string, data: rpc.Sequenceable): Promise\|向通用组件Callee发送约定序列化数据。| -|callWithResult(method: string, data: rpc.Sequenceable): Promise\|向通用组件Callee发送约定序列化数据, 并将返回的约定序列化数据带回。| +|callWithResult(method: string, data: rpc.Sequenceable): Promise\|向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。| |release(): void|释放通用组件的Caller通信接口。| |onRelease(callback: OnReleaseCallBack): void|注册通用组件通信断开监听通知。| ## 开发步骤 +Call调用的开发步骤: +- 创建Callee被调用端。 +- 访问Callee被调用端。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 开发步骤章节中的示例代码片段是开发过程的步骤化展示,部分代码可能无法单独运行,完整工程代码请参考[相关实例](#相关实例)。 ### 创建Callee被调用端 Callee被调用端,需要实现指定方法的数据接收回调函数、数据的序列化及反序列化方法。在需要接收数据期间,通过on接口注册监听,无需接收数据时通过off接口解除监听。 -1. 配置Ability的启动模式 +**1. 配置Ability的启动模式** - 配置module.json5,将Callee被调用端所在的Ability配置为单实例"singleton"。 + 配置module.json5,将CalleeAbility配置为单实例"singleton"。 |Json字段|字段说明| |:------|:------| @@ -51,11 +70,11 @@ Ability配置标签示例如下: "visible": true }] ``` -2. 导入Ability模块。 -``` +**2. 导入Ability模块** +```ts import Ability from '@ohos.application.Ability' ``` -3. 定义约定的序列化数据。 +**3. 定义约定的序列化数据** 调用端及被调用端发送接收的数据格式需协商一致,如下示例约定数据由number和string组成。具体示例代码如下: ```ts @@ -81,7 +100,7 @@ export default class MySequenceable { } } ``` -4. 实现Callee.on监听及Callee.off解除监听。 +**4. 实现Callee.on监听及Callee.off解除监听** 被调用端Callee的监听函数注册时机, 取决于应用开发者。注册监听之前的数据不会被处理,取消监听之后的数据不会被处理。如下示例在Ability的onCreate注册'MSG_SEND_METHOD'监听,在onDestroy取消监听,收到序列化数据后作相应处理并返回,应用开发者根据实际需要做相应处理。具体示例代码如下: ```ts @@ -89,12 +108,12 @@ const TAG: string = '[CalleeAbility]' const MSG_SEND_METHOD: string = 'CallSendMsg' function sendMsgCallback(data) { - Logger.log(TAG, 'CalleeSortFunc called') + console.log('CalleeSortFunc called') // 获取Caller发送的序列化数据 let receivedData = new MySequenceable(0, '') data.readSequenceable(receivedData) - Logger.log(TAG, `receiveData[${receivedData.num}, ${receivedData.str}]`) + console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`) // 作相应处理 // 返回序列化数据result给Caller @@ -106,7 +125,7 @@ export default class CalleeAbility extends Ability { try { this.callee.on(MSG_SEND_METHOD, sendMsgCallback) } catch (error) { - Logger.error(TAG, `${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) } } @@ -121,14 +140,26 @@ export default class CalleeAbility extends Ability { ``` ### 访问Callee被调用端 -1. 导入Ability模块。 -``` +**1. 导入Ability模块** +```ts import Ability from '@ohos.application.Ability' ``` -2. 获取Caller通信接口。 +**2. 获取Caller通信接口** Ability的context属性实现了startAbilityByCall方法,用于获取指定通用组件的Caller通信接口。如下示例通过`this.context`获取Ability实例的context属性,使用startAbilityByCall拉起Callee被调用端并获取Caller通信接口,注册Caller的onRelease监听。应用开发者根据实际需要做相应处理。具体示例代码如下: ```ts +// 注册caller的release监听 +private regOnRelease(caller) { + try { + caller.onRelease((msg) => { + console.log(`caller onRelease is called ${msg}`) + }) + console.log('caller register OnRelease succeed') + } catch (error) { + console.log(`caller register OnRelease failed with ${error}`) + } +} + async onButtonGetCaller() { try { this.caller = await context.startAbilityByCall({ @@ -136,41 +167,40 @@ async onButtonGetCaller() { abilityName: 'CalleeAbility' }) if (this.caller === undefined) { - Logger.error(TAG, 'get caller failed') + console.log('get caller failed') return } - Logger.log(TAG, 'get caller success') + console.log('get caller success') this.regOnRelease(this.caller) } catch (error) { - Logger.error(TAG, `get caller failed with ${error}`) + console.log(`get caller failed with ${error}`) } -}.catch((error) => { - console.error(TAG + 'get caller failed with ' + error) -}) +} ``` 在跨设备场景下,需指定对端设备deviceId。具体示例代码如下: ```ts -let TAG = '[MainAbility] ' -var caller = undefined -let context = this.context - -context.startAbilityByCall({ - deviceId: getRemoteDeviceId(), - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' -}).then((data) => { - if (data != null) { - caller = data - console.log(TAG + 'get remote caller success') - // 注册caller的release监听 - caller.onRelease((msg) => { - console.log(TAG + 'remote caller onRelease is called ' + msg) - }) - console.log(TAG + 'remote caller register OnRelease succeed') - } -}).catch((error) => { - console.error(TAG + 'get remote caller failed with ' + error) -}) +async onButtonGetRemoteCaller() { + var caller = undefined + var context = this.context + + context.startAbilityByCall({ + deviceId: getRemoteDeviceId(), + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }).then((data) => { + if (data != null) { + caller = data + console.log('get remote caller success') + // 注册caller的release监听 + caller.onRelease((msg) => { + console.log(`remote caller onRelease is called ${msg}`) + }) + console.log('remote caller register OnRelease succeed') + } + }).catch((error) => { + console.error(`get remote caller failed with ${error}`) + }) +} ``` 从DeviceManager获取指定设备的deviceId,getTrustedDeviceListSync接口仅对系统应用开放。具体示例代码如下: ```ts @@ -178,29 +208,31 @@ import deviceManager from '@ohos.distributedHardware.deviceManager'; var dmClass; function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { - var list = dmClass.getTrustedDeviceListSync(); + var list = dmClass.getTrustedDeviceListSync() if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); - return; + console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null") + return } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; + console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) + return list[0].deviceId } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null") } } ``` 在跨设备场景下,需要向用户申请数据同步的权限。具体示例代码如下: ```ts -let context = this.context -let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) -}) +requestPermission() { + let context = this.context + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] + context.requestPermissionsFromUser(permissions).then((data) => { + console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) + }).catch((error) => { + console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) + }) +} ``` -3. 发送约定序列化数据 +**3. 发送约定序列化数据** 向被调用端发送Sequenceable数据有两种方式,一种是不带返回值,一种是获取被调用端返回的数据,method以及序列化数据需要与被调用端协商一致。如下示例调用Call接口,向Callee被调用端发送数据。具体示例代码如下: ```ts @@ -210,7 +242,7 @@ async onButtonCall() { let msg = new MySequenceable(1, 'origin_Msg') await this.caller.call(MSG_SEND_METHOD, msg) } catch (error) { - Logger.error(TAG, `caller call failed with ${error}`) + console.log(`caller call failed with ${error}`) } } ``` @@ -224,27 +256,29 @@ async onButtonCallWithResult(originMsg, backMsg) { try { let msg = new MySequenceable(1, originMsg) const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg) - Logger.log(TAG, 'caller callWithResult succeed') + console.log('caller callWithResult succeed') let result = new MySequenceable(0, '') data.readSequenceable(result) backMsg(result.str) - Logger.log(TAG, `caller result is [${result.num}, ${result.str}]`) + console.log(`caller result is [${result.num}, ${result.str}]`) } catch (error) { - Logger.error(TAG, `caller callWithResult failed with ${error}`) + console.log(`caller callWithResult failed with ${error}`) } } ``` -4. 释放Caller通信接口 +**4. 释放Caller通信接口** Caller不再使用后,应用开发者可以通过release接口释放Caller。具体示例代码如下: ```ts -try { - this.caller.release() - this.caller = undefined - Logger.log(TAG, 'caller release succeed') -} catch (error) { - Logger.error(TAG, `caller release failed with ${error}`) +releaseCall() { + try { + this.caller.release() + this.caller = undefined + console.log('caller release succeed') + } catch (error) { + console.log(`caller release failed with ${error}`) + } } ``` diff --git a/zh-cn/application-dev/application-dev-guide-for-gitee.md b/zh-cn/application-dev/application-dev-guide-for-gitee.md index e17831a387db2b9ff959a3cf458369760f0545e6..79371930d291fc6452179a1f11f65c0f83f670c1 100644 --- a/zh-cn/application-dev/application-dev-guide-for-gitee.md +++ b/zh-cn/application-dev/application-dev-guide-for-gitee.md @@ -56,9 +56,8 @@ API参考提供了OpenHarmony全量组件和接口的参考文档,可以帮助 内容包括: - [组件参考(基于TS扩展的声明式开发范式)](reference/arkui-ts/Readme-CN.md) - - - [组件参考(基于JS扩展的类Web开发范式)](reference/arkui-js/Readme-CN.md) +- [JS服务卡片UI组件参考](reference/js-service-widget-ui/Readme-CN.md) - 接口参考 - [JS及TS API参考](reference/apis/Readme-CN.md) - Native API diff --git a/zh-cn/application-dev/application-dev-guide.md b/zh-cn/application-dev/application-dev-guide.md index 1a2dba85bb227a47c8a76fcdd2872190a184c585..b9cef5ddb5958576b70755b6b02fe4cd172fad72 100644 --- a/zh-cn/application-dev/application-dev-guide.md +++ b/zh-cn/application-dev/application-dev-guide.md @@ -60,6 +60,8 @@ API参考提供了OpenHarmony全量组件和接口的参考文档,可以帮助 - [组件参考(基于JS扩展的类Web开发范式)](reference/arkui-js/Readme-CN.md) +- [JS服务卡片UI组件参考](reference/js-service-widget-ui/Readme-CN.md) + - [接口参考(JS及TS API)](reference/apis/js-apis-DataUriUtils.md) - 接口参考(Native API) diff --git a/zh-cn/application-dev/database/database-datashare-guidelines.md b/zh-cn/application-dev/database/database-datashare-guidelines.md index c730616e533b82c03ac7acc927658afa34150e08..b41a1e4e611988cc7f4c404c5c8c40b9212dcf09 100644 --- a/zh-cn/application-dev/database/database-datashare-guidelines.md +++ b/zh-cn/application-dev/database/database-datashare-guidelines.md @@ -80,7 +80,7 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 } // 重写query接口 - query(uri, predicates, columns, callback) { + query(uri, predicates, columns, callback) { if (predicates == null || predicates == undefined) { console.info('invalid predicates'); } @@ -152,7 +152,7 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { abilityContext = this.context; - dataShare.createDataShareHelper(abilityContext, dseUri, (err,data)=>{ + dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{ dsHelper = data; }); } @@ -172,19 +172,19 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 {"name": "WangWu", "age": 21, "Binary": arr}, {"name": "ZhaoLiu", "age": 61, "Binary": arr}); // 插入一条数据 - dsHelper.insert(dseUri, valuesBucket, (err,data) => { + dsHelper.insert(dseUri, valuesBucket, (err, data) => { console.log("dsHelper insert result: " + data); }); // 删除指定的数据 - dsHelper.delete(dseUri, da, (err,data) => { + dsHelper.delete(dseUri, da, (err, data) => { console.log("dsHelper delete result: " + data); }); // 更新数据 - dsHelper.update(dseUri, da, updateBucket, (err,data) => { + dsHelper.update(dseUri, da, updateBucket, (err, data) => { console.log("dsHelper update result: " + data); }); // 查询数据 - dsHelper.query(dseUri, da, valArray, (err,data) => { + dsHelper.query(dseUri, da, valArray, (err, data) => { console.log("dsHelper query result: " + data); }); ``` diff --git a/zh-cn/application-dev/database/database-mdds-guidelines.md b/zh-cn/application-dev/database/database-mdds-guidelines.md index 6558bc98420f88eb0696e9c1cfb0413959ab1d6b..60a6256d8b2288f38058c660acc105fdb6017b7b 100644 --- a/zh-cn/application-dev/database/database-mdds-guidelines.md +++ b/zh-cn/application-dev/database/database-mdds-guidelines.md @@ -57,7 +57,7 @@ kvManager = manager; }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error: " + e); } ``` @@ -86,7 +86,7 @@ kvStore = store; }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error: " + e); } ``` @@ -120,7 +120,7 @@ console.log("put success"); }); }catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error: " + e); } ``` @@ -144,7 +144,7 @@ }); }); }catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error: " + e); } ``` @@ -176,7 +176,7 @@ // 1000表示最大延迟时间为1000ms kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); }catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error: " + e); } } }); diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md index 234b24caae2ee2e9b75671991ec458079a83755d..5d5f32cb857f74f88682ef11febaf3f8c46e12b1 100644 --- a/zh-cn/application-dev/database/database-relational-guidelines.md +++ b/zh-cn/application-dev/database/database-relational-guidelines.md @@ -198,7 +198,7 @@ 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",} + 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.') @@ -215,7 +215,7 @@ ```js var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} + const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8} let insertPromise = rdbStore.insert("test", valueBucket) ``` @@ -387,6 +387,5 @@ ## 相关实例 针对关系型数据库开发,有以下相关实例可供参考: -- [`Rdb`:关系型数据库(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb) - [`DistributedRdb`:分布式关系型数据库(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) - [关系型数据库(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/Readme-CN.md b/zh-cn/application-dev/faqs/Readme-CN.md new file mode 100644 index 0000000000000000000000000000000000000000..7eeb2c756aed17a3bb8ddbdfd5a30e0bef9e9513 --- /dev/null +++ b/zh-cn/application-dev/faqs/Readme-CN.md @@ -0,0 +1,15 @@ +# 常见问题 + +- [Ability框架开发常见问题](faqs-ability.md) +- [UI框架(JS)开发常见问题](faqs-ui-js.md) +- [UI框架(eTS)开发常见问题](faqs-ui-ets.md) +- [图形图像开发常见问题](faqs-graphics.md) +- [文件管理开发常见问题](faqs-file-management.md) +- [网络与连接开发常见问题](faqs-connectivity.md) +- [数据管理开发常见问题](faqs-data-management.md) +- [设备管理开发常见问题](faqs-device-management.md) +- [Native API使用常见问题](faqs-native.md) +- [三四方库使用常见问题](faqs-third-party-library.md) +- [IDE使用常见问题](faqs-ide.md) +- [hdc_std命令使用常见问题](faqs-hdc-std.md) +- [开发板](faqs-development-board.md) diff --git a/zh-cn/application-dev/faqs/faqs-ability.md b/zh-cn/application-dev/faqs/faqs-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..c8fcee56a3176f91010ecbcf880cea9885a7ae75 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-ability.md @@ -0,0 +1,62 @@ +# Ability框架开发常见问题 + + + +## Stage模型中是否有类似FA模型的DataAbility的开发指导文档 + +适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 + +Stage模型中DataShareExtensionAbility提供了向其他应用共享以及管理其数据的方法。 + +参考文档:[数据共享开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/database-datashare-guidelines.md) + +## 拉起Ability为什么在界面上没反应? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +1. 如果是通过startAbility的方式拉起,检查want中abilityName字段是否携带了bundleName做前缀,如果有,请删除; + +2. 检查MainAbility.ts文件中onWindowStageCreate方法配置的Ability首页文件是否在main_pages.json中有定义,如果没有定义,请补齐; + +3. SDK和OpenHarmony SDK系统推荐同一天的版本。 + +参考文档:[OpenHarmony版本转测试信息](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/Release-Testing-Version.md) + +## 调用方法的时候,如何解决方法内部的this变成undefined? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +方式一:在调用方法的时候加上.bind(this); + +方式二:使用箭头函数。 + +## 如何解决must have required property 'startWindowIcon'报错 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +Ability配置中缺少startWindowIcon属性配置,需要在module.json5中abilities中配置startWindowIcon。 + +参考文档:[Stage模型配置文件](https://docs.openharmony.cn/pages/v3.2Beta/zh-cn/application-dev/quick-start/stage-structure.md/) + + 示例: + +``` +{ + "module": { + // do something + "abilities": [{ + // do something + "startWindowIcon": "$media:space", + "startWindowBackground": "$color:white", + }] + } +} +``` + +## 如何获取设备横竖屏的状态变化的通知 + +适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 + +使用Ability的onConfigurationUpdated回调实现,系统语言、颜色模式以及Display相关的参数,比如方向、Density,发生变化时触发该回调。 + +参考文档:[Ability开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ability/stage-ability.md) diff --git a/zh-cn/application-dev/faqs/faqs-connectivity.md b/zh-cn/application-dev/faqs/faqs-connectivity.md new file mode 100644 index 0000000000000000000000000000000000000000..8690d9c205472b021b38799bf519fdde37a87aa9 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-connectivity.md @@ -0,0 +1,31 @@ +# 网络与连接开发常见问题 + + + +## Post请求时,extraData支持哪几种的数据格式? + +适用于:OpenHarmony SDK 3.2.2.5版本, API9 Stage模型 + +extraData代表发送请求的额外数据,支持如下数据: + +1. 当HTTP请求为POST、PUT方法时,此字段为HTTP请求的content。 + +2. 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。 + +3. 开发者传入string对象,开发者需要自行编码,将编码后的string传入。 + +## 如何理解http请求的错误码28? + +适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 + +错误码28代表CURLE_OPERATION_TIMEDOUT 。网络请求底层使用libcurl库,更多错误码可以查看相应文档。 + +参考文档:[开发指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-http.md#response%E5%B8%B8%E7%94%A8%E9%94%99%E8%AF%AF%E7%A0%81)和[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) + +## \@ohos.net.http.d.ts的response错误码返回6是什么意思? + +适用于:OpenHarmony SDK 3.2.3.5版本 + +6表示地址无法解析主机,可以尝试ping一下request中的url,确认是否可以ping通。 + +更多错误码参考[Response常用错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-http.md#response%E5%B8%B8%E7%94%A8%E9%94%99%E8%AF%AF%E7%A0%81)或者[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) diff --git a/zh-cn/application-dev/faqs/faqs-data-management.md b/zh-cn/application-dev/faqs/faqs-data-management.md new file mode 100644 index 0000000000000000000000000000000000000000..bdeef869a7c52819b9634b1d5a4432d41c20118c --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-data-management.md @@ -0,0 +1,24 @@ +# 数据管理开发常见问题 + + + +## 如何将PixelMap的数据存储到数据库中。 + +适用于:OpenHarmony SDK 3.2.3.5版本 + +PixelMap应该被转换成相应的ArrayBuffer再放进数据库。 + +参考文档:[readPixelsToBuffer](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md#readpixelstobuffer7-1) + +## 如何获取rdb关系型数据库文件 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +开发者可使用hdc_std命令拷贝文件,其中文件路径为: /data/app/el2/100/database/包名/entry/db/ ,然后拷贝该路径下后缀为 .db、.db-shm、.db-wal的文件,拷贝完成后,可以通过SQLite工具打开该数据库文件。 + +示例: + + +``` + hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db +``` diff --git a/zh-cn/application-dev/faqs/faqs-development-board.md b/zh-cn/application-dev/faqs/faqs-development-board.md new file mode 100644 index 0000000000000000000000000000000000000000..3ab491c0dc6b42b0ca2e91e7a55965f51f9d34ad --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-development-board.md @@ -0,0 +1,51 @@ +# 开发板 + + + +## 如何获取开发板上截屏图片? + +适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 + +- 方法一:点击开发板下拉控制中心的截屏按钮,截屏图片通过相册可以查看。 + +- 方法二:通过截屏脚本一键截屏,可以在电脑上查看。操作方法:Windows上连接开发板,然后电脑上新建文本文件,拷贝如下脚本内容,文件名后缀改为.bat文件(需要提前配置好hdc的环境变量),点击运行后,截屏图片与脚本在同一目录。 + 示例: + + + ``` + set filepath=/data/%date:~0,4%%date:~5,2%%date:~8,2%%time:~1,1%%time:~3,2%%time:~6,2%.png + echo %filepath% + : pause + hdc_std shell snapshot_display -f %filepath% + : pause + hdc_std file recv %filepath% . + : pause + ``` + +## RK3568板子和previewer上展示的效果差异较大,如何把previewer的尺寸调整成实际板子一样。 + +适用于:IDE 3.0.0.991 + +1. 给预览器新建Profile + ![zh-cn_image_0000001361254285](figures/zh-cn_image_0000001361254285.png) + +2. 新建Profile的具体参数可参考如下配置: + Device type : default + + Resolution: 720\*1280 + + DPI: 240 + +## 开发板安装驱动后设备仍然无法识别,设备管理器错误识别为其他设备:FT232R USB UART () + +可能原因:开发版的USB串口驱动没有安装。 + +解决办法:搜索FT232R USB UART确定,下载安装驱动即可。 + +## 在开发板上登录需要认证网络如何进行认证 + +适用于:OpenHarmony SDK 3.2.2.5版本 + +连接需要认证的网络后,用浏览器打开任意网址就可以进入认证页面。 + +如果开发板上没有浏览器,可以安装[浏览器Sample应用](https://gitee.com/openharmony/app_samples/tree/master/device/Browser)。 diff --git a/zh-cn/application-dev/faqs/faqs-device-management.md b/zh-cn/application-dev/faqs/faqs-device-management.md new file mode 100644 index 0000000000000000000000000000000000000000..b5bac9f878fb9e5bbe7732479e97c478df7dfc5d --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-device-management.md @@ -0,0 +1,24 @@ +# 设备管理开发常见问题 + + + +## 如何获取设备的dpi值 + +适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 + +导入@ohos.display包,通过getDefaultDisplay方法获取。 + +示例: + + +``` +import display from '@ohos.display'; +display.getDefaultDisplay((err, data) => { + if (err.code) { + console.error('Test Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Test Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + console.info('Test densityDPI:' + JSON.stringify(data.densityDPI)); +});https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-device-info.md) +``` diff --git a/zh-cn/application-dev/faqs/faqs-file-management.md b/zh-cn/application-dev/faqs/faqs-file-management.md new file mode 100644 index 0000000000000000000000000000000000000000..a6caa4a7064430e4b0c2a2fb49523a8a433ec564 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-file-management.md @@ -0,0 +1,36 @@ +# 文件管理开发常见问题 + + + +## 调用媒体库getAlbums方法,没有收到返回,也没有捕获到异常是为什么 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +getAlbums方法需要权限:ohos.permission.READ_MEDIA,从[OpenHarmony权限定义列表](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.md)查询知道ohos.permission.READ_MEDIA权限是需要用户授权。 + +1. 在module.json5中配置权限: + + ``` + "requestPermissions": [ + { + "name": "ohos.permission.READ_MEDIA" + } + ] + ``` + +2. 在MainAbility.ts -> onWindowStageCreate页面加载前需要增加用户授权代码: + + ``` + private requestPermissions() { + let permissionList: Array = [ + "ohos.permission.READ_MEDIA" + ]; + this.context.requestPermissionsFromUser(permissionList) + .then(data => { + console.info(`request permission data result = ${data.authResults}`) + }) + .catch(err => { + console.error(`fail to request permission error:${err}`) + }) + } + ``` diff --git a/zh-cn/application-dev/faqs/faqs-graphics.md b/zh-cn/application-dev/faqs/faqs-graphics.md new file mode 100644 index 0000000000000000000000000000000000000000..f72711aefb13db79150b749d9a3e6ed470597d0c --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-graphics.md @@ -0,0 +1,15 @@ +# 图形图像开发常见问题 + + + +## 调用window实例的setSystemBarProperties接口时,设置isStatusBarLightIcon和isNavigationBarLightIcon属性不生效 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +状态栏字体高亮属性的本质就只是让字体变成白色。调用window实例的setSystemBarProperties接口时,如果设置了状态栏内容颜色statusBarContentColor,就以开发者设置的颜色为准,isStatusBarLightIcon状态栏字体高亮属性就不生效;同理,如果设置了导航栏内容颜色navigationBarContentColor,isNavigationBarLightIcon导航栏字体高亮属性就不生效。 + +## 如何设置系统状态栏样式 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +导入\@ohos.window模块,开发者可以使用window.setSystemBarProperties()接口设置状态栏样式属性,达到自定义样式的效果。 diff --git a/zh-cn/application-dev/faqs/faqs-hdc-std.md b/zh-cn/application-dev/faqs/faqs-hdc-std.md new file mode 100644 index 0000000000000000000000000000000000000000..90f627289b2fcefa4d9e62d23249f22ed7e597c2 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-hdc-std.md @@ -0,0 +1,63 @@ +# hdc_std命令使用常见问题 + + + +## 日志的常用命令 + +适用于:OpenHarmony SDK 3.2.2.5版本 + +清理日志:hdc_std shell hilog -r + +调大缓存到20M:hdc_std shell hilog -G 20M + +抓取日志:hdc_std shell hilog > log.txt + +## 日志限流怎么规避 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +- 关闭日志限流 hdc_std shell hilog -Q pidoff + +- 关闭隐私标志 hdc_std shell hilog -p off + +- 增加日志buffer hdc_std shell hilog -G 200M + +- 关闭全局日志,只打开自己领域的日志 hdc_std shell hilog –b D –D 0xd0xxxxx + +执行完命令后重启DevEco Studio。 + +## 应用如何打印日志是使用hilog还是console,hilog接口参数domain的设置范围是什么? + +适用于:OpenHarmony SDK 3.2.2.5版本 + +推荐使用[hilog日志系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-hilog.md)进行日志打印,接口参数domain的设置范围可以参考[开发指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-hilog.md#hilogisloggable)。 + +## hilog日志打印长度限制是多少,是否可以配置 + +适用于:OpenHarmony SDK 3.2.2.5版本 + +日志打印的长度限制为1024,该长度不能配置。 + +## 为什么有时候直接用IDE安装HAP包到开发板上无法打开? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +请检查sdk和开发板烧录的系统版本是否一致,推荐取同一天的sdk和系统版本。 + +## 如何通过hdc命令上传文件 + +适用于:OpenHarmony SDK 3.2.2.5版本 + +可以使用hdc_std file send上传文件。 + +## 如何让RK3568开发板不熄屏? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +输入命令hdc_std shell "power-shell setmode 602" + +## 如何通过命令启动Ability? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +输入命令hdc_std shell aa start -a AbilityName -b bundleName -m moduleName diff --git a/zh-cn/application-dev/faqs/faqs-ide.md b/zh-cn/application-dev/faqs/faqs-ide.md new file mode 100644 index 0000000000000000000000000000000000000000..c9b32df07511cccbb9c1607d5bb121b635372457 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-ide.md @@ -0,0 +1,19 @@ +# IDE使用常见问题 + + + +## 如何解决报错“npm ERR! code SELF_SIGNED_CERT_IN_CHAIN”? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +1. 在Dev Eco Studio terminal中执行npm config set strict-ssl=false; + +2. 在Dev Eco Studio terminal中执行npm install。 + +## 手工更新DevEco的SDK后,编译HAP报错“Cannot find module 'xxx\ets\x.x.x.x\build-tools\ets-loader\node_modules\webpack\bin\webpack.js'” + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +1. 到SDK的ets\x.x.x.x\build-tools\ets-loader目录下执行npm install; + +2. 到SDK的js\x.x.x.x\build-tools\ace-loader目录下执行npm install。 完成步骤后重新编辑既可。 diff --git a/zh-cn/application-dev/faqs/faqs-native.md b/zh-cn/application-dev/faqs/faqs-native.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf66a518dc8e55090fceb0b4d3858c22c814703 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-native.md @@ -0,0 +1,57 @@ +# Native API使用常见问题 + + + +## 运行Native HAP的时候,导入的命名空间报错Obj is not a valid object + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +检查模块根目录(注意不是工程根目录)下的build-profile.json5文件,如果设备是32位,需要在abiFilters参数中配置armeabi-v7a,如果设备是64位,需要在abiFilters参数中配置arm64-v8a。 + +## NAPI开发的C++代码中,如何获取到模块 package.json 文件中的 “version” 值? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +1. 在编译工具Hvigor脚本文件hvigorfile.js中,通过subModule.getPackageJsonPath方法获取module中package.json文件位置; + +2. 使用nodejs能力读取package.json文件中version字段,写入build-profile.json5文件buildOption.cppFlags字段; + +示例: + + +``` +// module hvigorfile.js +const subModule = require('@ohos/hvigor')(__filename) + +const fs = require("fs-extra") +const path = require("path") + +const packageJsonPath = subModule.getPackageJsonPath() +const buildProfilePath = path.resolve(packageJsonPath, '../build-profile.json5') +const packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) +let buildProfileData = fs.readFileSync(buildProfilePath, 'utf8') +buildProfileData = buildProfileData.replace(/\"cppFlags\"\:(.*)\,/, `"cppFlags": "-D NWEBEX_VERSION=${packageJsonData.version}",`) +fs.writeFileSync(buildProfilePath, buildProfileData, 'utf8') + +const ohosPlugin = require('@ohos/hvigor-ohos-plugin').hapTasks(subModule) // 该插件执行了C++编译任务,读取了build-profile.json5文件 + +module.exports = { + ohos: ohosPlugin +} +``` + + +``` +// hellp.cpp 读取 +#define _NWEBEX_VERSION(v) #v +#define _NWEBEX_VER2STR(v) _NWEBEX_VERSION(v) + +static napi_value Add(napi_env env, napi_callback_info info) +{ + + napi_value fixed_version_value = nullptr; + napi_create_string_utf8(env, _NWEBEX_VER2STR(NWEBEX_VERSION), NAPI_AUTO_LENGTH, &fixed_version_value); + + return fixed_version_value; +} +``` diff --git a/zh-cn/application-dev/faqs/faqs-third-party-library.md b/zh-cn/application-dev/faqs/faqs-third-party-library.md new file mode 100644 index 0000000000000000000000000000000000000000..758305d4aca128e8d39001b2176c3f820f2302e2 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-third-party-library.md @@ -0,0 +1,9 @@ +# 三四方库使用常见问题 + + + +## 报错“Stage model module … does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed. ”是什么意思? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +三四方件未适配API9 Stage模型,无法使用。 diff --git a/zh-cn/application-dev/faqs/faqs-ui-ets.md b/zh-cn/application-dev/faqs/faqs-ui-ets.md new file mode 100644 index 0000000000000000000000000000000000000000..cd53f334c0463202a548a20158e27318923230b3 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-ui-ets.md @@ -0,0 +1,282 @@ +# UI框架(eTS)开发常见问题 + + + +## TS语言在生成器函数中编译失败,有哪些使用限制? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +TS语言的使用在生成器函数中存在以下限制: + +- 表达式仅允许在字符串(${expression})、if条件、ForEach的参数和组件的参数中使用; + +- 这些表达式中的任何一个都不能导致任何应用程序状态变量(\@State、\@Link、\@Prop)的改变,否则会导致未定义和潜在不稳定的框架行为; + +- 生成器函数内部不能有局部变量。 + +上述限制都不适用于事件处理函数(例如onClick)的匿名函数实现。 + +错误示例: + + +``` +build() { + let a: number = 1 // invalid: variable declaration not allowed + Column() { + Text('Hello ${this.myName.toUpperCase()}') // ok. + ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array varible in place + } + buildSpecial() // invalid: no function calls + Text(this.calcTextValue()) // this function call is ok. +} +``` + +## 在Stage模型下,如何通过router实现页面跳转 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +1. 对于通过页面路由router实现页面跳转,首先要在main_pages.json配置文件中将所有跳转的页面加入pages列表; + +2. 页面路由需要在页面渲染完成之后才能调用,在onInit和onReady生命周期中页面还处于渲染阶段,禁止调用页面路由方法。 + +## router通过调用push方法进堆栈的page是否会被回收 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +调用push进入堆栈的page不回收,调用back方法出栈后可以被回收。 + +## 如何动态替换掉资源文件中的“%s”占位符 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +在应用中,通过"$r('app.string.xx')"的形式引用应用资源,$r的第二个参数可用于替换%s占位符。 + + 示例: + +``` +build() { + //do something + //引用的string资源,$r的第二个参数用于替换%s + Text($r('app.string.entry_desc','aaa')) + .fontSize(100) + .fontColor(Color.Black) + //do something +} +``` + +## 如何读取Resource中的xml文件并转化为String类型 + +适用于:OpenHarmony SDK 3.2.2.5版本, API9 Stage模型 + +1. 通过resourceManager的RawFile接口获取Uint8Array格式数据。 + +2. 通过String.fromCharCode将Uint8Array格式数据转化为String类型。 + +参考文档:[资源管理](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md) + +示例: + + +``` +resourceManager.getRawFile(path, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + let xml = String.fromCharCode.apply(null, rawFile) + } +}); +``` + +## 如何将Resource资源对象转成string类型 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +通过\@ohos.resourceManager模块 resourceManager.getString()方法获取字符串。 + +参考文档:[资源管理](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md#getstring) + +## class全局静态变量无法使用的问题 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +Page和Ability打包后会对import的对象分别形成两个不同的闭包,即打包出两个Global对象。因此,所引用的静态变量并不是同一对象,所以无法通过class静态变量方式定义全局变量。建议使用AppStorage进行全局变量管理。 + +参考文档:[应用程序的数据存储](https://docs.openharmony.cn/pages/v3.2Beta/zh-cn/application-dev/ui/ts-application-states-appstorage.md/) + +## Stage模型下如何获取资源 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +Stage模型支持了通过context获取resourceManager对象的方式,再调用其内部获取资源的接口,无需再导入包,此方式FA模型不适用。 + +示例: + + +``` +const context = getContext(this) as any +context + .resourceManager + .getString($r('app.string.entry_desc').id) + .then(value => { + this.message = value.toString() +}) +``` + +## 如何将容器定位到屏幕的最底部? + +适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 + +可以使用Stack堆叠容器,设置子组件在容器内的最底部。 + + 示例: + +``` +build() { + Stack({alignContent : Alignment.Bottom}) { + //容器位于最底部 + Stack() { + Column() + .width('100%') + .height('100%') + .backgroundColor(Color.Yellow) + } + .width('100%') + .height('10%') + } + .width('100%') + .height('100%') + .backgroundColor('rgba(255,255,255, 0)') +} +``` + +## CustomDialog是否支持在TS文件中使用? + +适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 + +不支持,CustomDialog当前只支持在eTS的Page中使用。 + +参考文档:[自定义弹窗](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## 如何将CustomDialog中的变量传递给Page页面中的变量? + +适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 + +利用自定义的回调函数,当点击弹窗的confirm按钮时,将data数据从自定义弹窗组件中传递给当前的page的页面。 + +示例: + + +``` +// CustomDialog 组件 +@CustomDialog +struct MyDialog { + controller: CustomDialogController + title: string + data: string + cancel: () => void + confirm: (data: string) => void + Button('confirm') + .onClick(() => { + this.controller.close() + this.data = 'test' + this.confirm(this.data) + }).backgroundColor(0xffffff).fontColor(Color.Red) +// Page页面 +@Entry +@Component +struct DialogTest { + dialogController: CustomDialogController = new CustomDialogController({ + builder: MyDialog({ title:'标题自定义',cancel: this.onCancel, + confirm: this.onAccept.bind(this) }), // 绑定自定义的回调函数 + cancel: this.existApp, + autoCancel: true + }) + onAccept(data:string) { + console.info('Callback when the second button is clicked ' + data) + } +} +``` + +## List组件上添加了Text组件后,List组件无法拖动到底部 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +在List的父容器加上代码layoutWeight(1)。原理:List属于可滚动容器组件,默认高度是占满全屏幕高度,当出现其他固定高度的组件占领了屏幕的部分高度时,需要开发人员显性的指定List组件占满剩余高度,而不是全屏幕高度。 + +## 栅格布局子组件如何居中? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +GridContainer内子组件默认水平左对齐,居中显示可以参考以下处理方式: + +内部嵌套布局组件Row,设置Row属性justifyContent(FlexAlign.Center),内部嵌套子组件可保持居中显示,参考[栅格布局](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md)文档。 + + 示例: + +``` +GridContainer({ sizeType: SizeType.SM, columns: 12 }) { + Row() { + Text('1') + .useSizeType({ + sm: { span: 4, offset: 0 }, + }) + .backgroundColor(0x46F2B4) + }.justifyContent(FlexAlign.Center) // 该属性设置使子组件居中显示 +} +``` + +## 如何获取状态栏和导航栏高度? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +在加载窗口内容之前,采用systemAvoidAreaChange事件监听。 + + 示例: + +``` +// MainAbility.ts +import window from '@ohos.window'; + +/** + * 设置沉浸式窗口,并获取状态栏和导航栏高度 + * @param mainWindow 主窗口对象 + */ +async function enterImmersion(mainWindow: window.Window) { + mainWindow.on("systemAvoidAreaChange", (area: window.AvoidArea) => { + AppStorage.SetOrCreate("topHeight", area.topRect.height); + AppStorage.SetOrCreate("bottomHeight", area.bottomRect.height); + }) + await mainWindow.setFullScreen(true) + await mainWindow.setSystemBarEnable(["status", "navigation"]) + await mainWindow.setSystemBarProperties({ + navigationBarColor: "#00000000", + statusBarColor: "#00000000", + navigationBarContentColor: "#FF0000", + statusBarContentColor: "#FF0000" + }) +} +export default class MainAbility extends Ability { + // do something + async onWindowStageCreate(windowStage: window.WindowStage) { + let mainWindow = await windowStage.getMainWindow() + await enterImmersion(mainWindow) + windowStage.loadContent('pages/index') + } + // do something +} +``` + +## 如何在eTS代码中执行Web组件内的JS函数? + +适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 + +通过WebController中runJavaScript方法异步执行JavaScript脚本,并通过回调方式返回脚本执行的结果。注意:runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 + +参考文档:[Web](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md) + +## 在容器组件嵌套的场景下,如何解决手势拖拽事件出现错乱的问题? + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +gesture的属性distance默认值是5,把gesture的属性distance设成1就可以解决。 diff --git a/zh-cn/application-dev/faqs/faqs-ui-js.md b/zh-cn/application-dev/faqs/faqs-ui-js.md new file mode 100644 index 0000000000000000000000000000000000000000..390b9e3753099a245a1395f9fc8e82ff7f271675 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-ui-js.md @@ -0,0 +1,96 @@ +# UI框架(JS)开发常见问题 + + + +## 如何取出xml文件中对应的字段 + +适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 + +convertxml中convert方法提供了转换xml文本为JavaScript对象的能力。 + +示例: + + +``` +import convertxml from '@ohos.convertxml'; +// 代码片段 +xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let conv = new convertxml.ConvertXML(); +// 转换选项, 参考文档使用 +let options = {trim : false, declarationKey:"_declaration", + instructionKey : "_instruction", attributesKey : "_attributes", + textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", + commentKey : "_comment", parentKey : "_parent", typeKey : "_type", + nameKey : "_name", elementsKey : "_elements"} +let result:any = conv.convert(xml, options) // 将xml文本转为JS对象 +console.log('Test: ' + JSON.stringify(result)) +console.log('Test: ' + result._declaration._attributes.version) // xml代码片段version字段信息 +console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // xml代码片段title字段内容 +``` + +参考文档:[xml转换JavaScript](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-convertxml.md) + +## JS、TS和eTS的区别 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +- JS:Web 的编程语言。具有轻量级,弱类型等特点。 + +- TS:TS是JS的超集,拓展了JS的语法。有明确的类型与更多面向对象的内容如接口,枚举等。 + +- eTS:OpenHarmony UI开发框架语言,是对TS的扩展,通过声明式开发范式实现UI界面。 + +## 如何将时间转为时分秒格式 + +示例: + + +``` +export default class DateTimeUtil{ + /** + * 时分秒 + */ + getTime() { + const DATETIME = new Date() + return this.concatTime(DATETIME.getHours(),DATETIME.getMinutes(),DATETIME.getSeconds()) + } + /** + * 年月日 + */ + getDate() { + const DATETIME = new Date() + return this.concatDate(DATETIME.getFullYear(),DATETIME.getMonth()+1,DATETIME.getDate()) + } + /** + * 日期不足两位补充0 + * @param value-数据值 + */ + fill(value:number) { + return (value> 9 ? '' : '0') + value + } + /** + * 年月日格式修饰 + * @param year + * @param month + * @param date + */ + concatDate(year: number, month: number, date: number){ + return `${year}${this.fill(month)}${this.fill(date)}` + } + /** + * 时分秒格式修饰 + * @param hours + * @param minutes + * @param seconds + */ + concatTime(hours:number,minutes:number,seconds:number){ + return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}` + } +} +``` diff --git a/zh-cn/application-dev/faqs/figures/zh-cn_image_0000001361254285.png b/zh-cn/application-dev/faqs/figures/zh-cn_image_0000001361254285.png new file mode 100644 index 0000000000000000000000000000000000000000..bbce36c81db4c07075a8f91075842b6f33f35b34 Binary files /dev/null and b/zh-cn/application-dev/faqs/figures/zh-cn_image_0000001361254285.png differ diff --git a/zh-cn/application-dev/internationalization/intl-guidelines.md b/zh-cn/application-dev/internationalization/intl-guidelines.md index 0f3584a39921fe3065bc46b3ae296c297267442f..ffd0b98fc45ad1e6973b9e1f2435650f86656408 100644 --- a/zh-cn/application-dev/internationalization/intl-guidelines.md +++ b/zh-cn/application-dev/internationalization/intl-guidelines.md @@ -37,14 +37,6 @@ | kn | 表示字符串排序、比较时是否考虑数字的实际值 | | kf | 表示字符串排序、比较时是否考虑大小写 | -| 扩展参数ID | 扩展参数说明 | -| -------- | -------- | -| ca | 表示日历系统 | -| co | 表示排序规则 | -| hc | 表示守时惯例 | -| nu | 表示数字系统 | -| kn | 表示字符串排序、比较时是否考虑数字的实际值 | -| kf | 表示字符串排序、比较时是否考虑大小写 | ```js var locale = "zh-CN"; diff --git a/zh-cn/application-dev/media/image.md b/zh-cn/application-dev/media/image.md index deda457636e444120cee5a4577ebe1fed567b5fa..1042fc7e915a9fd9e719c3e443b0f77d1cb32f56 100644 --- a/zh-cn/application-dev/media/image.md +++ b/zh-cn/application-dev/media/image.md @@ -267,7 +267,7 @@ imageSourceApi.getImageInfo(imageInfo => { }) // 用于更新增量数据 -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {}) +imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error, data)=> {}) ``` diff --git a/zh-cn/application-dev/notification/background-agent-scheduled-reminder-guide.md b/zh-cn/application-dev/notification/background-agent-scheduled-reminder-guide.md index 309b35884a463fa5048b1ea03ae70a27a472ecdf..13b3a3f980fd2addecea4f3d960fd0de031a4e3e 100644 --- a/zh-cn/application-dev/notification/background-agent-scheduled-reminder-guide.md +++ b/zh-cn/application-dev/notification/background-agent-scheduled-reminder-guide.md @@ -26,7 +26,8 @@ enum ActionButtonType: 在提醒弹出的通知界面上的按钮的类型。 | 枚举名 | 描述 | | -------- | -------- | -| ACTION_BUTTON_TYPE_CLOSE | 指明是close按钮,点击后关闭当前提醒的铃声(如果正在响铃),关闭提醒的通知,取消延迟提醒。 | +| ACTION_BUTTON_TYPE_CLOSE | 关闭按钮。关闭提醒的通知,取消延迟提醒。如果正在响铃,点击后会关闭当前提醒的铃声。 | +| ACTION_BUTTON_TYPE_SNOOZE | 延迟按钮。点击当前的提醒会延迟相应时间。 | enum ReminderType: 提醒类型 diff --git a/zh-cn/application-dev/quick-start/syscap.md b/zh-cn/application-dev/quick-start/syscap.md index 202957bcc518d852301259ae3e3881a32bd6995a..861052c8c41e22e90ea9654707e5dd6423314fb3 100644 --- a/zh-cn/application-dev/quick-start/syscap.md +++ b/zh-cn/application-dev/quick-start/syscap.md @@ -39,6 +39,12 @@ SDK 提供全量的 API 给 IDE,IDE 通过开发者的项目支持的设备, ## SysCap开发指导 +### PCID获取 + +PCID,全称 Product Compatibility ID,包含当前设备支持的 syscap 信息。获取所有设备 PCID 的认证中心正在建设中,目前需要找对应设备的厂商获取该设备的 PCID。 + + + ### PCID导入 DevEco Studio 工程支持 PCID 的导入。导入的 PCID 文件解码后输出的 syscap 会被写入 syscap.json 文件中。 @@ -55,34 +61,30 @@ IDE 会根据创建的工程所支持的设置自动配置联想能力集和要 对于联想能力集,开发者通过添加更多的系统能力,在 IDE 中可以使用更多的 API,但要注意这些 API 可能在设备上不支持,使用前需要判断。 对于要求能力集,开发者修改时要十分慎重,修改不当会导致应用无法分发到目标设备上。 -``` +```json /* syscap.json */ { - devices: { - general: [ /*每一个典型设备对应一个syscap支持能力集,可配置多个典型设备*/ + "devices": { + "general": [ /*每一个典型设备对应一个syscap支持能力集,可配置多个典型设备*/ "default", - "car, - ... + "car" ], - custom: [ /*厂家自定义设备*/ + "custom": [ /*厂家自定义设备*/ { "某自定义设备": [ - "SystemCapability.Communication.SoftBus.Core", - ... + "SystemCapability.Communication.SoftBus.Core" ] - }, - ... + } ] }, - development: { /*addedSysCaps内的sycap集合与devices中配置的各设备支持的syscap集合的并集共同构成联想能力集*/ - addedSysCaps: [ - "SystemCapability.Location.Location.Lite", - ... + "development": { /*addedSysCaps内的sycap集合与devices中配置的各设备支持的syscap集合的并集共同构成联想能力集*/ + "addedSysCaps": [ + "SystemCapability.Location.Location.Lite" ] }, - production: { /*用于生成rpcid,慎重添加,可能导致应用无法分发到目标设备上*/ - addedSysCaps: [], //devices中配置的各设备支持的syscap集合的交集,添加addedSysCaps集合再除去removedSysCaps集合,共同构成要求能力集 - removedSysCaps: [] //当该要求能力集为某设备的子集时,应用才可被分发到该设备上 + "production": { /*用于生成rpcid,慎重添加,可能导致应用无法分发到目标设备上*/ + "addedSysCaps": [], //devices中配置的各设备支持的syscap集合的交集,添加addedSysCaps集合再除去removedSysCaps集合,共同构成要求能力集 + "removedSysCaps": [] //当该要求能力集为某设备的子集时,应用才可被分发到该设备上 } } ``` diff --git a/zh-cn/application-dev/reference/Readme-CN.md b/zh-cn/application-dev/reference/Readme-CN.md index fb4b5ce23d9743a121f179a5ab6470713323e2c9..62258182f16f280828c947c9ed7173d1a4acdd5d 100644 --- a/zh-cn/application-dev/reference/Readme-CN.md +++ b/zh-cn/application-dev/reference/Readme-CN.md @@ -2,6 +2,7 @@ - [组件参考(基于TS扩展的声明式开发范式)](arkui-ts/Readme-CN.md) - [组件参考(基于JS扩展的类Web开发范式)](arkui-js/Readme-CN.md) +- [JS服务卡片UI组件参考](js-service-widget-ui/Readme-CN.md) - [接口参考(JS及TS API)](apis/Readme-CN.md) - 接口参考(Native API) - [OpenHarmony Native API](native-apis/Readme-CN.md) diff --git a/zh-cn/application-dev/reference/apis/development-intro.md b/zh-cn/application-dev/reference/apis/development-intro.md index d2e3b7ad38b4714ceced8bfae159de35d07e6406..b8ff2b41d4857406933513cf95b1138b27a8cada 100644 --- a/zh-cn/application-dev/reference/apis/development-intro.md +++ b/zh-cn/application-dev/reference/apis/development-intro.md @@ -21,6 +21,10 @@ Ability是系统调度应用的最小单元,是能够完成一个独立功能 OpenHarmony中提供的接口,部分是仅供OEM厂商使用的system api,普通应用无法使用。 +普通应用即应用APL等级为normal的应用。默认情况下,应用的等级都为normal应用。 + +APL等级的详细说明及如何将应用的APL等级声明为normal以上,请参考[访问控制开发概述-应用APL等级说明](../../security/accesstoken-overview.md#应用apl等级说明)。 + 针对这种情况,在文档中会进行系统接口的声明: - 如果某个模块的接口均为system api,会在文档开头说明:该模块接口为系统接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md index 8f55340eb2cb325aaa413616cd1425903835dd35..e6d07583cb3deb335f0bfe68c7748ee31c408025 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md @@ -888,7 +888,7 @@ disconnectAbility(connection: number, callback:AsyncCallback\): void; startAbilityByCall(want: Want): Promise<Caller>; -获取指定通用组件服务端的caller通信接口, 并且将指定通用组件服务端拉起并切换到后台。 +启动指定Ability至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -896,7 +896,7 @@ startAbilityByCall(want: Want): Promise<Caller>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | 传入需要启动的ability的信息,包含ability名称、包名、设备ID,设备ID缺省或为空表示启动本地ability。 | +| want | [Want](js-apis-application-Want.md) | 是 | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId(可选)、parameters(可选),其中deviceId缺省或为空表示启动本地Ability,parameters缺省或为空表示后台启动Ability。 | **返回值:** @@ -907,22 +907,40 @@ startAbilityByCall(want: Want): Promise<Caller>; **示例:** ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); + let caller = undefined; + + // 后台启动Ability,不配置parameters + var wantBackground = { + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "" + }; + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + caller = obj; + console.log('GetCaller success'); + }).catch((error) => { + console.log(`GetCaller failed with ${error}`); + }); + + // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true + var wantForeground = { + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "", + parameters: { + "ohos.aafwk.param.callAbilityToForeground": true } - } + }; + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + caller = obj; + console.log('GetCaller success'); + }).catch((error) => { + console.log(`GetCaller failed with ${error}`); + }); ``` ## AbilityContext.startAbilityWithAccount diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index 347fb90a3897cfd8b25d44c40574ad9869e3bee4..d44fca75d3d6629aed6a7fa89e1cdf124b73c010 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -1,4 +1,4 @@ -# 应用帐号管理 +# 应用帐号管理 本模块不仅用于对应用帐号的添加、删除、查询、修改和授权,且提供帐号将数据写入磁盘和数据同步的能力。 @@ -154,7 +154,7 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a } const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccountImplicitly("LiSi", "readAge", {}, { + appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -321,7 +321,8 @@ enableAppAccess(name: string, bundleName: string): Promise<void> **示例:** ```js - app_account_instance.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { console.log('enableAppAccess Success'); }).catch((err) => { console.log("enableAppAccess err: " + JSON.stringify(err)); @@ -334,7 +335,7 @@ checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): 检查指定应用帐号是否允许应用数据同步,使用callback回调异步返回结果。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount @@ -361,7 +362,7 @@ checkAppAccountSyncEnable(name: string): Promise<boolean> 检查指定应用帐号是否允许应用数据同步,使用Promise方式异步返回结果。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount @@ -510,7 +511,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback 设置指定的应用程序帐号是否允许应用程序数据同步,使用callback回调异步返回结果。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount @@ -537,7 +538,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> 设置指定的应用程序帐号是否允许应用程序数据同步,使用Promise方式异步返回结果。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount @@ -585,7 +586,8 @@ setAssociatedData(name: string, key: string, value: string, callback: AsyncCallb **示例:** ```js - app_account_instance.setAssociatedData("ZhangSan", "k001", "v001", (err) => { + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { console.log("setAssociatedData err: " + JSON.stringify(err)); }); ``` @@ -1010,7 +1012,7 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri } const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "readAge", {}, { + appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -1037,7 +1039,7 @@ getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCall ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", (err, data) => { + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthToken err: ' + JSON.stringify(err)); console.log('getOAuthToken token: ' + data); }); @@ -1069,7 +1071,7 @@ getOAuthToken(name: string, owner: string, authType: string): Promise<string& ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge").then((data) => { + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthToken token: ' + data); }).catch((err) => { console.log("getOAuthToken err: " + JSON.stringify(err)); @@ -1097,7 +1099,7 @@ setOAuthToken(name: string, authType: string, token: string, callback: AsyncCall ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx", (err) => { + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -1128,7 +1130,7 @@ setOAuthToken(name: string, authType: string, token: string): Promise<void> ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx").then(() => { + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { console.log('setOAuthToken successfully'); }).catch((err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); @@ -1157,7 +1159,7 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string, c ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx", (err) => { + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -1189,7 +1191,7 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string): ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx").then(() => { + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { console.log('deleteOAuthToken successfully'); }).catch((err) => { console.log("deleteOAuthToken err: " + JSON.stringify(err)); @@ -1218,7 +1220,7 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err) => { + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -1250,7 +1252,7 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then(() => { + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -1278,7 +1280,7 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, ca ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err, data) => { + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); console.log('checkOAuthTokenVisibility isVisible: ' + data); }); @@ -1310,7 +1312,7 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): P ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then((data) => { + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -1395,7 +1397,7 @@ getOAuthList(name: string, authType: string, callback: AsyncCallback<Array< ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge", (err, data) => { + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthList err: ' + JSON.stringify(err)); console.log('getOAuthList data: ' + JSON.stringify(data)); }); @@ -1426,7 +1428,7 @@ getOAuthList(name: string, authType: string): Promise<Array<string>> ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge").then((data) => { + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { console.log("getOAuthList err: " + JSON.stringify(err)); @@ -1462,7 +1464,7 @@ getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<Authentic } var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); }); @@ -1498,7 +1500,7 @@ getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { @@ -1967,8 +1969,8 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---------- | | owner | string | 是 | 认证器的所有者包名。 | -| iconId | string | 是 | 认证器的图标标识。 | -| labelId | string | 是 | 认证器的标签标识。 | +| iconId | number | 是 | 认证器的图标标识。 | +| labelId | number | 是 | 认证器的标签标识。 | ## SelectAccountsOptions9+ @@ -2082,7 +2084,7 @@ onResult: (code: number, result: {[key: string]: any}) => void appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 5b3992e4556c3ac86289f9e745a3321c675b57cd..505b86f9912b6bc535bcccafe69e6cd34f3fc253 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -13,7 +13,7 @@ ## 导入模块 -``` +```js import audio from '@ohos.multimedia.audio'; ``` @@ -32,7 +32,7 @@ getAudioManager(): AudioManager | [AudioManager](#audiomanager) | 音频管理类。 | **示例:** -``` +```js var audioManager = audio.getAudioManager(); ``` @@ -50,7 +50,7 @@ getStreamManager(): AudioStreamManager | [AudioStreamManager](#audiostreammanager9) | 返回音频流管理器实例。 | **示例:** -``` +```js var audioStreamManager = audio.getStreamManager(); ``` @@ -71,7 +71,7 @@ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\ **示例:** -``` +```js import audio from '@ohos.multimedia.audio'; var audioStreamInfo = { @@ -170,7 +170,7 @@ createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback