diff --git a/CODEOWNERS b/CODEOWNERS index 9464d41605519160d1a0652ac9fa556be2dcae73..9ab1bb5c83f55ef5bba1b76c4e29e0690b72eb12 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -200,9 +200,9 @@ zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShi zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 -zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-battery-info.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 -zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-brightness.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-buffer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515 @@ -322,7 +322,7 @@ zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @han-zhengshi @ge-yaf zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-pointer.md @yuanxinying @ningningW @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-power.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-power.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengyawen @shuqinglin2 @jinhaihw zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen @@ -335,7 +335,7 @@ zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @ zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world -zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-runninglock.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw @@ -350,9 +350,9 @@ zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @f zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-system-app.md @HelloCrease @niulihua @tomatodevboy -zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-system-battery.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 -zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984 @@ -375,7 +375,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ningni zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong -zh-cn/application-dev/reference/apis/js-apis-thermal.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-thermal.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-timer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-shortKey.md @mayunteng_1 @ningningW @cococoler @alien0208 @@ -426,7 +426,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @littl zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-avsession.md @liuyuehua1 @zengyawen @saga2020 @currydavids -zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515 diff --git a/en/application-dev/database/data-persistence-by-preferences.md b/en/application-dev/database/data-persistence-by-preferences.md index 553050a55a585dc34e620623eb187a0365b8488e..593eeea535a48a0d6795c4d996691fb1c87626f3 100644 --- a/en/application-dev/database/data-persistence-by-preferences.md +++ b/en/application-dev/database/data-persistence-by-preferences.md @@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md). - | API | Description | -|--------------------------------------------------------------------------------------------------|------------------------------------------------------------| -| getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void | Obtain a **Preferences** instance. | -| putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. | -| hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. | -| getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. | -| deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. | -| flush(callback: AsyncCallback<void>): void | Flushes the data of this **Preferences** instance to a file for data persistence. | -| on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. | -| off(type: 'change', callback?: Callback<{ key : string }>): void | Unsubscribes from data changes. | -| deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file.| +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void | Obtains a **Preferences** instance. | +| putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. | +| hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. | +| getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. | +| deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. | +| flush(callback: AsyncCallback<void>): void | Flushes the data of this **Preferences** instance to a file for data persistence. | +| on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. | +| off(type: 'change', callback?: Callback<{ key : string }>): void | Unsubscribes from data changes. | +| deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file. | ## How to Develop 1. Import the **@ohos.data.preferences** module. - + ```js import dataPreferences from '@ohos.data.preferences'; ``` @@ -55,14 +55,16 @@ The following table lists the APIs used for persisting user preference data. For Stage model: - + ```js import UIAbility from '@ohos.app.ability.UIAbility'; + import { BusinessError } from '@ohos.base'; + import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => { + dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => { if (err) { console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); return; @@ -79,15 +81,16 @@ The following table lists the APIs used for persisting user preference data. For FA model: - + ```js import featureAbility from '@ohos.ability.featureAbility'; + import { BusinessError } from '@ohos.base'; // Obtain the context. let context = featureAbility.getContext(); try { - dataPreferences.getPreferences(context, 'mystore', (err, preferences) => { + dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => { if (err) { console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); return; @@ -102,7 +105,7 @@ The following table lists the APIs used for persisting user preference data. For 3. Write data. - Use **putSync()** to write data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary. + Use **putSync()** to save data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary. > **NOTE** > @@ -110,7 +113,7 @@ The following table lists the APIs used for persisting user preference data. For Example: - + ```js try { if (preferences.hasSync('startup')) { @@ -142,7 +145,7 @@ The following table lists the APIs used for persisting user preference data. For Use **deleteSync()** to delete a KV pair.
Example: - + ```js try { preferences.deleteSync('startup'); @@ -157,7 +160,7 @@ The following table lists the APIs used for persisting user preference data. For ```js try { - preferences.flush((err) => { + preferences.flush((err: BusinessError) => { if (err) { console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); return; @@ -174,18 +177,20 @@ The following table lists the APIs used for persisting user preference data. For Specify an observer as the callback to return the data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. Example: ```js - let observer = function (key) { - console.info('The key' + key + 'changed.'); + interface observer { + key: string } - preferences.on('change', observer); + preferences.on('change', (key: observer) => { + console.info('The key' + key + 'changed.'); + }); // The data is changed from 'auto' to 'manual'. - preferences.put('startup', 'manual', (err) => { + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`); return; } console.info("Succeeded in putting the value of 'startup'."); - preferences.flush((err) => { + preferences.flush((err: BusinessError) => { if (err) { console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); return; @@ -207,10 +212,10 @@ The following table lists the APIs used for persisting user preference data. For Example: - + ```js try { - dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => { + dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { if (err) { console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`); return; diff --git a/en/application-dev/database/data-sync-of-distributed-data-object.md b/en/application-dev/database/data-sync-of-distributed-data-object.md index d620fae702fd1559e07114e2e650a03248179bcd..79f0078f3b9bf63a023997305af6d191c0a5e927 100644 --- a/en/application-dev/database/data-sync-of-distributed-data-object.md +++ b/en/application-dev/database/data-sync-of-distributed-data-object.md @@ -3,26 +3,30 @@ ## When to Use -To implement traditional data synchronization between devices, you need to design the message processing logic, including setting up a communication link, sending, receiving, and processing messages, retry mechanism upon errors, and resolving data conflicts. The workload is heavy. In addition, the debugging complexity increases with the number of devices. +The traditional implementation of data synchronization between devices involves heavy workload. You need to design the message processing logic for setting up a communication link, sending, receiving, and processing messages, and resolving data conflicts, as well as retry mechanism upon errors. In addition, the debugging complexity increases with the number of devices. -The device status, message sending progress, and data transmitted are variables. If these variables support global access, they can be accessed as local variables on difference devices. This simplifies data synchronization between multiple devices. +The device status, message sending progress, and data transmitted are variables. If these variables support global access, they can be accessed as local variables by difference devices. This simplifies data synchronization across devices. -The distributed data object (**DataObject**) implements global access to variables. **DataObject** provides basic data object management capabilities and distributed capabilities. You can use the APIs to create, query, delete, and modify in-memory objects and subscribe to event notifications. OpenHarmony also provides easy-to-use JS APIs for distributed application scenarios to easily implement cross-device data collaboration for the same application. In addition, object status and data changes on different devices can be observed. This feature implements data object collaboration for the same application between multiple devices that form a Super Device. **DataObject** greatly reduces the development workloads compared with the traditional mode. +The distributed data object (**distributedDataObject**) module implements global access to variables. It provides basic data object management capabilities, including creating, querying, deleting, and modifying in-memory objects and subscribing to data or status changes. It also provides distributed capabilities. OpenHarmony provides easy-to-use JS APIs for distributed application scenarios. With these APIs, you can easily implement data collaboration for an application across devices and listening for status and data changes between devices. The **distributedDataObject** module implements data object collaboration for the same application across multiple devices that form a Super Device. It greatly reduces the development workloads compared with the traditional implementation. ## Basic Concepts -- Distributed in-memory database
- The distributed in-memory database caches data in the memory so that applications can quickly access data without persisting data. If the database is closed, the data is not retained. +- Distributed in-memory database + + +The distributed in-memory database caches data in the memory so that applications can quickly access data without persisting data. If the database is closed, the data is not retained. - Distributed data object - A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **get()** and **put()** operations in the corresponding database, respectively. + - The distributed data object can be in the following states in its lifecycle: +A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading and writing a distributed data object are mapped to the **get** and **put** operations in the corresponding database, respectively. - - **Uninitialized**: The distributed data object is not instantiated or has been destroyed. - - **Local**: The data table is created, but the data cannot be synchronized. - - **Distributed**: The data table is created, and there are at least two online devices with the same session ID. In this case, data can be synchronized across devices. If a device is offline or the session ID is empty, the distributed data object changes to the local state. +The distributed data object has the following states in its lifecycle: + + - **Uninitialized**: The distributed data object is not instantiated or is destroyed. + - **Local**: A data table is created, but the data cannot be synchronized. + - **Distributed**: A data table is created, and data can be synchronized (there are at least two online devices with the same session ID). If a device is offline or the session ID is empty, the distributed data object changes to the local state. ## Working Principles @@ -31,201 +35,221 @@ The distributed data object (**DataObject**) implements global access to variabl ![distributedObject](figures/distributedObject.jpg) -The distributed data objects are encapsulated into JS objects in distributed in-memory databases. This allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization. +The distributed data objects are encapsulated JS objects in distributed in-memory databases, and can be operated in the same way as local variables. The system automatically implements data synchronization across devices. -### JS Object Storage and Encapsulation Mechanism +### Encapsulation and Storage of JS Objects - An in-memory database is created for each distributed data object instance and identified by a session ID (**SessionId**). The in-memory databases created for different applications are isolated from each other. -- When a distributed data object is instantiated, all properties of the object are traversed recursively. **Object.defineProperty** is used to define the **set()** and **get()** methods of all properties. The **set()** and **get()** methods correspond to the **put** and **get** operations of a record in the database, respectively. **Key** specifies the property name, and **Value** specifies the property value. +- When a distributed data object is instantiated, all properties of the object are traversed recursively. **Object.defineProperty** is used to define the **set()** and **get()** methods for all properties. The **set()** and **get()** methods correspond to the **put** and **get** operations of a record in the database, respectively. **Key** specifies the property name, and **Value** specifies the property value. -- When a distributed data object is read or written, the **set()** and **get()** methods are automatically called to perform the related operations to the database. +- When a distributed data object is read or written, the **get()** or **set()** method is automatically called to perform the related operation on data in the database. **Table 1** Correspondence between a distributed data object and a distributed database - -| Distributed Data Object Instance| Object Instance| Property Name| Property Value| + +| Distributed Data Object Instance| Object Instance| Property Name| Property Value| | -------- | -------- | -------- | -------- | -| Distributed in-memory database| Database identified by **sessionID**| Key of a record in the database| Value of a record in the database| +| Distributed in-memory database| Database identified by **sessionID**| Key of a record in the database| Value of a record in the database| -### Cross-Device Synchronization and Data Change Notification Mechanism +### Cross-Device Synchronization and Data Change Notification -The distributed data object is used to implement data synchronization between objects. You can create a distributed data object and set **sessionID** for the devices on a trusted network. The distributed data objects with the same **sessionID** on different devices can synchronize data with each other. +One of the most important functions of distributed data objects is to implement data synchronization between objects. Distributed data objects are created locally for the devices on a trusted network. If the distributed data objects on different devices are set with the same **sessionID**, data can be synchronized between them. -As shown in the following figure, distributed data object 1 on device A and device B have the same session ID **session1**. The synchronization relationship of session1 is established between the two objects. +As shown in the following figure, distributed data object 1 of device A and distributed data object 1 of device B are set with the same session ID **session1**, and synchronization relationship of session 1 is established between the two objects. - **Figure 2** Object synchronization relationship +**Figure 2** Object synchronization relationship ![distributedObject_sync](figures/distributedObject_sync.jpg) -For each device, only one object can be added to a synchronization relationship. As shown in the preceding figure, distributed data object 2 of device A cannot be added to session 1 because distributed data object 1 of device A has been added to session 1. +For each device, only one distributed data object can be added to a synchronization relationship. As shown in the preceding figure, distributed data object 2 of device A cannot be added to session 1 because distributed data object 1 of device A has been added to session 1. + +After the synchronization relationship is established, each session has a copy of shared object data. The distributed data objects added to a session support the following operations: -After the synchronization relationship is established, each session has a copy of shared object data. The distributed data objects added to the same session support the following operations: +- Reading or modifying the data in the session. - (1) Reading or modifying the data in the session. +- Listening for data changes made by other devices. - (2) Listening for data changes made by other devices. +- Listening for status changes, such as the addition and removal of other devices. - (3) Listening for status changes, such as the addition and removal of other devices. -### Minimum Unit to Synchronize +### Minimum Synchronization Unit -Attribute is the minimum unit to synchronize in distributed data objects. For example, object 1 in the following figure has three attributes: name, age, and parents. If one of the attributes is changed, only the changed attribute needs to be synchronized. +Property is the minimum unit to synchronize in distributed data objects. For example, object 1 in the following figure has three properties: name, age, and parents. If one of the properties is changed, only the changed attribute needs to be synchronized. **Figure 3** Synchronization of distributed data objects - + ![distributedObject_syncView](figures/distributedObject_syncView.jpg) -### Object Persistence Mechanism +### Persistence of Distributed Data Objects -Distributed data objects run in the process space of applications. When the data of a distributed data object is persisted in the distributed database, the data will not be lost after the application exits. +Distributed data objects run in the process space of applications. After the data of a distributed data object is persisted in the distributed database, the data will not be lost after the application exits. You need to persist distributed data objects in the following scenarios: -- Enable an application to retrieve the exact same data after it is opened again. In this case, you need to persist the distributed data object (for example, object 1). After the application is opened again, create a distributed data object (for example, object 2) and set the session ID of object 1 for object 2. Then, the application can retrieve the data of object 1. +- Enable an application to retrieve the exact same data after it starts again. In this case, you need to persist the distributed data object (for example, object 1 with session ID 1). After the application starts again, create a distributed data object (for example, object 2) and set the session ID to 1. Then, the application can retrieve the data of object 1. -- Enable an application opened on another device to retrieve the exact same data. In this case, you need to persist the distributed data object (for example, object 1) on device A and synchronize the data to device B. Then, create a distributed data object (for example, object 2) and set the session ID of object 1 for object 2. When the application is opened on device B, it can retrieve the same application data used on device A before the application is closed. +- Enable an application started on another device to retrieve the exact same data. In this case, you need to persist the distributed data object (for example, object 1 with session ID 1) on device A and synchronize the data to device B. Then, create a distributed data object (for example, object 2) and set the session ID to 1. When the application is started on device B, it can retrieve the same application data used on device A before the application is closed. ## Constraints -- Data synchronization can be implemented across devices only for the applications with the same **bundleName**. +- Only the data of the same application can be synchronized across devices, that is, the devices must have the same **bundleName**. -- Data can be synchronized only for the distributed data objects with the same **sessionID** of the same application. +- Data can be synchronized for the distributed data objects with the same session ID. - Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects. - The maximum size of a distributed data object is 500 KB. -- It takes about 50 ms from the time when 1 KB of data starts to be modified on a device to the time when another device receives a data change notification. +- If data of 1 KB data is modified on device A, device B can complete data update within 50 ms after receiving a data change notification. - A maximum of 16 distributed data object instances can be created for an application. -- For optimal performance and user experience, the maximum number of devices for data collaboration is 3. +- For the sake of performance and user experience, the maximum number of devices for data collaboration is 3. -- For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. +- For the distributed data object of the complex type, only the root property can be modified. The subordinate properties cannot be modified. -- Only JS APIs are supported. +- Currently, only JS APIs are supported. ## Available APIs -The following table lists the APIs for cross-device synchronization of distributed data objects. Most of the interfaces are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). +Most of the APIs for cross-device synchronization of distributed data objects are executed asynchronously in callback or promise mode. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). -| API| Description| +| API| Description| | -------- | -------- | -| create(context: Context, source: object): DataObject | Creates a distributed data object instance.| -| genSessionId(): string | Generates a session ID for distributed data objects.| -| setSessionId(sessionId: string, callback: AsyncCallback<void>): void | Sets a session ID for data synchronization. Automatic synchronization is performed for devices with the same session ID on a trusted network.| -| setSessionId(callback: AsyncCallback<void>): void | Exits all sessions.| -| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void | Subscribes to data changes of this distributed data object.| -| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to status changes of this distributed data object.| -| save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void | Saves a distributed data object.| -| revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void | Revokes the save operation of the distributed data object.| +| create(context: Context, source: object): DataObject | Creates a distributed data object instance.| +| genSessionId(): string | Generates a session ID for distributed data objects.| +| setSessionId(sessionId: string, callback: AsyncCallback<void>): void | Sets a session ID for data synchronization. Automatic synchronization is performed for devices with the same session ID on a trusted network.| +| setSessionId(callback: AsyncCallback<void>): void | Exits all sessions.| +| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void | Subscribes to data changes of this distributed data object.| +| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to status changes of this distributed data object.| +| save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void | Saves a distributed data object.| +| revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void | Revokes the saving of the distributed data object.| ## How to Develop -The following example demonstrates how to implement a distributed data object synchronization. +The following example demonstrates how to implement synchronization of distributed data objects. 1. Import the **@ohos.data.distributedDataObject** module. - + ```js import distributedDataObject from '@ohos.data.distributedDataObject'; ``` -2. Request permissions. +2. Apply for required permissions. - 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + 1. Apply for the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). -3. Creates a distributed data object instance. +3. Create a distributed data object instance. Stage model: - + ```js // Import the module. import distributedDataObject from '@ohos.data.distributedDataObject'; import UIAbility from '@ohos.app.ability.UIAbility'; - + import { BusinessError } from '@ohos.base'; + import window from '@ohos.window'; + + interface sourceObject{ + name: string, + age: number, + isVis: boolean + parent: { [key: string]: string }, + list: { [key: string]: string }[] + } class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - // Create a distributed data object, which contains attributes of the string, number, boolean, and object types. - let localObject = distributedDataObject.create(this.context, { + onWindowStageCreate(windowStage: window.WindowStage) { + let source: sourceObject = { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - }); + } + let localObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, source); } } ``` FA model: - + ```js // Import the module. import distributedDataObject from '@ohos.data.distributedDataObject'; import featureAbility from '@ohos.ability.featureAbility'; // Obtain the context. let context = featureAbility.getContext(); - // Create a distributed data object, which contains attributes of the string, number, boolean, and object types. - let localObject = distributedDataObject.create(context, { + interface sourceObject{ + name: string, + age: number, + isVis: boolean + parent: { [key: string]: string }, + list: { [key: string]: string }[] + } + let source: sourceObject = { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - }); + } + // Create a distributed data object, which has properties of the string, number, boolean, and object types. + let localObject: distributedDataObject.DataObject = distributedDataObject.create(context, source); ``` 4. Set the same session ID for the distributed data objects for data synchronization. The data objects in the synchronization network include the local and remote objects. - + ```js // Set a session ID, for example, 123456, for device 1. - let sessionId = '123456'; + let sessionId: string = '123456'; localObject.setSessionId(sessionId); // Set the same session ID for device 2. - // Create a distributed data object, which contains attributes of the string, number, boolean, and object types. - let remoteObject = distributedDataObject.create(this.context, { + // Create a distributed data object, which has properties of the string, number, boolean, and object types. + let remoteSource: sourceObject = { name: undefined, age: undefined, // undefined indicates that the data comes from the peer end. isVis: true, parent: undefined, list: undefined - }); - // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. + } + let remoteObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, remoteSource); + // After learning that the device goes online, the remote object synchronizes data. That is, name is changed to jack and age to 18. remoteObject.setSessionId(sessionId); ``` 5. Observe data changes of a distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return a data change event. - - ```js - function changeCallback(sessionId, changeData) { - console.info(`change: ${sessionId}`); - if (changeData !== null && changeData !== undefined) { - changeData.forEach(element => { - console.info(`The element ${localObject[element]} changed.`); - }); - } + ```js + interface ChangeCallback { + sessionId: string, + fields: Array } - // To refresh the page in changeCallback, correctly bind (this) to the changeCallback. - localObject.on("change", this.changeCallback.bind(this)); + localObject.on("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info(`The element ${localObject[changeData.fields[index]]} changed.`); + } + } + }); ``` -6. Modify attributes of the distributed data object. The object attributes support basic data types (number, Boolean, and string) and complex data types (array and nested basic types). - +6. Modify properties of the distributed data object. The object properties support basic data types (number, Boolean, and string) and complex data types (array and nested basic types). + ```js localObject.name = 'jack1'; localObject.age = 19; @@ -236,9 +260,9 @@ The following example demonstrates how to implement a distributed data object sy > **NOTE** > - > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. + > For the distributed data object of the complex type, only the root property can be modified. The subordinate properties cannot be modified. - + ```js // Supported modification. localObject.parent = { mother: 'mom', father: 'dad' }; @@ -246,62 +270,82 @@ The following example demonstrates how to implement a distributed data object sy localObject.parent.mother = 'mom'; ``` -7. Access a distributed data object. Obtain the distributed data object attributes, which are the latest data on the network. - +7. Access a distributed data object. Obtain the distributed data object properties, which are the latest data on the network. + ```js console.info(`name:${localObject['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, this API unregisters all data change callbacks of the distributed data object. + ```js // Unregister this.changeCallback. - localObject.off('change', this.changeCallback); + localObject.off('change',(changeData: ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } + }); // Unregister all data change callbacks. localObject.off('change'); ``` -9. Subscribes to status changes of a distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. - +9. Subscribe to status changes of a distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. + ```js - function statusCallback(sessionId, networkId, status) { - // Service processing. + interface onStatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' } - localObject.on('status', this.statusCallback); + localObject.on('status', (statusCallback: onStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); + // Service processing. + }); ``` -10. Save a distributed data object and revoke the data saving operation. - +10. Save a distributed data object and revoke the data saved. + ```js // Save the data object if the device on the network needs to retrieve the object data after the application exits. - localObject.save('local').then((result) => { + localObject.save("local").then((result: distributedDataObject.SaveSuccessResponse) => { console.info(`Succeeded in saving. SessionId:${result.sessionId},version:${result.version},deviceId:${result.deviceId}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Failed to save. Code:${err.code},message:${err.message}`); }); - - // Revoke the save of a distributed data object. - localObject.revokeSave().then((result) => { + + // Revoke the data saved. + localObject.revokeSave().then((result: distributedDataObject.RevokeSaveSuccessResponse) => { console.info(`Succeeded in revokeSaving. Session:${result.sessionId}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Failed to revokeSave. Code:${err.code},message:${err.message}`); }); ``` 11. Unsubscribe from the status changes of a distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object. - + ```js + interface offStatusCallback { + sessionId: string, + deviceId: string, + status: 'online' | 'offline' + } // Unregister this.statusCallback. - localObject.off('status', this.statusCallback); + localObject.off('status', (statusCallback: offStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId); + // Service processing. + }); // Unregister all status change callbacks. localObject.off('status'); ``` 12. Remove a distributed data object from the synchronization network. The data of the removed distributed data object will not be synchronized to other devices. - + ```js localObject.setSessionId(() => { - console.info('leave all lession.'); + console.info('leave all session.'); }); - ``` + ``` \ No newline at end of file diff --git a/en/application-dev/database/data-sync-of-kv-store.md b/en/application-dev/database/data-sync-of-kv-store.md index b23dd91ed1a7b4ea0cd13f6d9b49de82e1821190..39f893f799a6a4c6bf9ac2d067a5f794a6961d9c 100644 --- a/en/application-dev/database/data-sync-of-kv-store.md +++ b/en/application-dev/database/data-sync-of-kv-store.md @@ -32,7 +32,7 @@ The underlying devices manage the data by device. The device KV stores support d The **DatamgrService** provides the following synchronization types: -- Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions. The manual synchronization is available only for system applications. +- Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions. - Automatic synchronization: The distributed database automatically pushes local data to the remote end and pulls remote data to the local end. An automatic synchronization is triggered when a device goes online or an application updates data. @@ -72,8 +72,6 @@ When data is added, deleted, or modified, a notification is sent to the subscrib - Each KV store supports a maximum of eight callbacks for subscription of data change notifications. -- The manual synchronization is available only for system applications. - ## Available APIs @@ -247,32 +245,31 @@ The following uses a single KV store as an example to describe how to implement > **NOTE** > - > If manual synchronization is used, **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications. + > If manual synchronization is used, **deviceIds** can be obtained by [devManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). - ```js - import deviceManager from '@ohos.distributedHardware.deviceManager'; + import deviceManager from '@ohos.distributedDeviceManager'; let devManager; - // create deviceManager - deviceManager.createDeviceManager('bundleName', (err, value) => { - if (!err) { - devManager = value; - // deviceIds is obtained by devManager.getTrustedDeviceListSync. - let deviceIds = []; - if (devManager !== null) { - // The ohos.permission.ACCESS_SERVICE_DM permission is required. This permission is available only for system applications. - let devices = devManager.getTrustedDeviceListSync(); - for (let i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } - } - try { - // 1000 indicates the maximum delay, in ms. - kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); - } catch (e) { - console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`); + try { + // create deviceManager + devManager = deviceManager.createDeviceManager(context.applicationInfo.name); + // deviceIds is obtained by devManager.getAvailableDeviceListSync. + let deviceIds = []; + if (devManager != null) { + let devices = devManager.getAvailableDeviceListSync(); + for (let i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; } } - }); + try { + // 1000 indicates the maximum delay, in ms. + kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); + } catch (e) { + console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`); + } + + } catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } ``` \ No newline at end of file diff --git a/en/application-dev/database/data-sync-of-rdb-store.md b/en/application-dev/database/data-sync-of-rdb-store.md index 2d6d5a73e0cf7cfae28d7d6296039e28994477a8..7bcc40f6230871e7e9a3af7150cd943b426109c1 100644 --- a/en/application-dev/database/data-sync-of-rdb-store.md +++ b/en/application-dev/database/data-sync-of-rdb-store.md @@ -10,9 +10,16 @@ You can synchronize the application data in a local RDB store on a device to oth OpenHamony supports synchronization of the relational data of an application across multiple devices. -- Distributed table list
After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name. +- Distributed table list -- Synchronization mode
Data can be synchronized between devices in either of the following ways:
- Pushing data from a local device to a remote device.
- Pulling data from a remote device to a local device. + After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name. + +- Synchronization mode + + Data can be synchronized between devices in either of the following ways: + + - Pushing data from a local device to a remote device. + - Pulling data from a remote device to a local device. ## Working Principles @@ -44,12 +51,10 @@ When data is added, deleted, or modified, a notification is sent to the subscrib - Each RDB store supports a maximum of eight callbacks for subscription of data change notifications. -- Third-party applications cannot call the distributed APIs that must be specified with the device. - ## Available APIs -The following table lists the APIs for cross-device data synchronization of RDB stores. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). +Most of the APIs for cross-device data synchronization of RDB stores are executed asynchronously in callback or promise mode. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). | API| Description| | -------- | -------- | @@ -73,7 +78,7 @@ The following table lists the APIs for cross-device data synchronization of RDB import relationalStore from '@ohos.data.relationalStore'; ``` -2. Request permissions. +2. Apply for the required permission. 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). @@ -142,32 +147,33 @@ The following table lists the APIs for cross-device data synchronization of RDB > **NOTE** > - > **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications. + > The value of **deviceIds** can be obtained by [deviceManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). ```js // Obtain device IDs. - import deviceManager from '@ohos.distributedHardware.deviceManager'; - - deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.info(`Failed to create device manager. Code:${err.code},message:${err.message}`); - return; - } - let devices = manager.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; - - // Construct a predicate object for querying the distributed table. - let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); - // Query data from the specified remote device and return the query result. - store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], - function (err, resultSet) { - if (err) { - console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); - return; - } - console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + import deviceManager from '@ohos.distributedDeviceManager'; + let dmInstance = null; + let deviceId = null; + + try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; + + // Construct a predicate object for querying the distributed table. + let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); + // Query data from the specified remote device and return the query result. + store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], + function (err, resultSet) { + if (err) { + console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); + return; } - ) - }) - ``` + console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + } + ) + } catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } + ``` \ No newline at end of file diff --git a/en/application-dev/database/share-data-by-datashareextensionability.md b/en/application-dev/database/share-data-by-datashareextensionability.md index d3c28e31c20f0aa3d6720359aa28e84af2061a63..6b6819d706a1aadfcb6ce854189321b57657e1b3 100644 --- a/en/application-dev/database/share-data-by-datashareextensionability.md +++ b/en/application-dev/database/share-data-by-datashareextensionability.md @@ -57,15 +57,16 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt 2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareExtAbility.ts**. -3. Import **@ohos.application.DataShareExtensionAbility** and other dependencies to the **DataShareExtAbility.ts** file, and -override the service implementation as required. For example, if the data provider provides only the data insertion, deletion, and query services, you can override only these APIs. - +3. Import **@ohos.application.DataShareExtensionAbility** and other dependencies to the **DataShareExtAbility.ts** file, and override the service implementation as required. For example, if the data provider provides only the data insertion, deletion, and query services, you can override only these APIs. + ```js import Extension from '@ohos.application.DataShareExtensionAbility'; import rdb from '@ohos.data.relationalStore'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; + import relationalStore from '@ohos.data.relationalStore'; + import Want from '@ohos.app.ability.Want'; ``` - + 4. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. ```js @@ -75,20 +76,20 @@ override the service implementation as required. For example, if the data provid + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)'; - let rdbStore; - let result; + let rdbStore: relationalStore.RdbStore; + let result: string; export default class DataShareExtAbility extends Extension { - private rdbStore_; + private rdbStore_: relationalStore.RdbStore; // Override onCreate(). - onCreate(want, callback) { + onCreate(want: Want, callback: Function) { result = this.context.cacheDir + '/datashare.txt'; // Create an RDB store. rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 - }, function (err, data) { + }, (err, data) => { rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`); @@ -100,7 +101,7 @@ override the service implementation as required. For example, if the data provid } // Override query(). - query(uri, predicates, columns, callback) { + query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) { if (predicates === null || predicates === undefined) { console.info('invalid predicates'); } @@ -188,6 +189,8 @@ override the service implementation as required. For example, if the data provid import UIAbility from '@ohos.app.ability.UIAbility'; import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; + import { ValuesBucket } from '@ohos.data.ValuesBucket' + import window from '@ohos.window'; ``` 2. Define the URI string for communicating with the data provider. @@ -200,11 +203,11 @@ override the service implementation as required. For example, if the data provid 3. Create a **DataShareHelper** instance. ```js - let dsHelper; - let abilityContext; + let dsHelper: dataShare.DataShareHelper; + let abilityContext: Context; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { abilityContext = this.context; dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => { dsHelper = data; @@ -217,8 +220,19 @@ override the service implementation as required. For example, if the data provid ```js // Construct a piece of data. - let valuesBucket = { 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) }; - let updateBucket = { 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) }; + let key1 = 'name'; + let key2 = 'age'; + let key3 = 'isStudent'; + let key4 = 'Binary'; + let valueName1 = 'ZhangSan'; + let valueName2 = 'LiSi'; + let valueAge1 = 21; + let valueAge2 = 18; + let valueIsStudent1 = false; + let valueIsStudent2 = true; + let valueBinary = new Uint8Array([1, 2, 3]); + let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary }; + let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary }; let predicates = new dataSharePredicates.DataSharePredicates(); let valArray = ['*']; // Insert a piece of data. @@ -237,5 +251,4 @@ override the service implementation as required. For example, if the data provid dsHelper.delete(dseUri, predicates, (err, data) => { console.info(`dsHelper delete result:${data}`); }); - ``` - + ``` \ No newline at end of file diff --git a/en/application-dev/database/unified-data-channels.md b/en/application-dev/database/unified-data-channels.md index b31b9532eafb700da67c2dbcc5464f8f58867d23..91201427f1807bb9ae002a43bf9757c26d7e2ffd 100644 --- a/en/application-dev/database/unified-data-channels.md +++ b/en/application-dev/database/unified-data-channels.md @@ -29,7 +29,7 @@ Currently, the UDMF provides the public data channel for cross-application data ## Available APIs -The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [UDMF](../reference/apis/js-apis-data-udmf.md). +The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [Unified Data Channel](../reference/apis/js-apis-data-unifiedDataChannel.md) and [Standard Data Definition and Description](../reference/apis/js-apis-data-uniformTypeDescriptor.md). | API | Description | |-----------------------------------------------------------------------------------------|---------------------------------------------| @@ -45,121 +45,131 @@ The following example describes how to implement many-to-many data sharing. The ### Data Provider -1. Import the **@ohos.data.UDMF** module. +1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules. ```ts - import UDMF from '@ohos.data.UDMF'; + import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; + import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; ``` 2. Create a **UnifiedData** object and insert it into the UDMF public data channel. ```ts - let plainText = new UDMF.PlainText(); + import { BusinessError } from '@ohos.base'; + let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; - let unifiedData = new UDMF.UnifiedData(plainText); + let unifiedData = new unifiedDataChannel.UnifiedData(plainText); // Specify the type of the data channel to which the data is to be inserted. - let options = { - intention: UDMF.Intention.DATA_HUB + let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB } try { - UDMF.insertData(options, unifiedData, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in inserting data. key = ${data}`); - } else { - console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); - } - }); - } catch(e) { - console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.insertData(options, unifiedData, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in inserting data. key = ${data}`); + } else { + console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); + } + }); + } catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `); } ``` 3. Update the **UnifiedData** object inserted. ```ts - let plainText = new UDMF.PlainText(); + import { BusinessError } from '@ohos.base'; + let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'How are you!'; - let unifiedData = new UDMF.UnifiedData(plainText); + let unifiedData = new unifiedDataChannel.UnifiedData(plainText); // Specify the URI of the UnifiedData object to update. - let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' + let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.updateData(options, unifiedData, (err) => { - if (err === undefined) { - console.info('Succeeded in updating data.'); - } else { - console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); - } - }); - } catch(e) { - console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.updateData(options, unifiedData, (err) => { + if (err === undefined) { + console.info('Succeeded in updating data.'); + } else { + console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); + } + }); + } catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `); } ``` 4. Delete the **UnifiedData** object from the UDMF public data channel. ```ts + import { BusinessError } from '@ohos.base'; // Specify the type of the data channel whose data is to be deleted. - let options = { - intention: UDMF.Intention.DATA_HUB + let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB }; - + try { - UDMF.deleteData(options, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in deleting data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } - } - } else { - console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + unifiedDataChannel.deleteData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in deleting data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); + } } - }); - } catch(e) { - console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); + } + } else { + console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + } + }); + } catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `); } ``` ### Data Consumer -1. Import the **@ohos.data.UDMF** module. +1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules. ```ts - import UDMF from '@ohos.data.UDMF'; + import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; + import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; ``` 2. Query the **UnifiedData** object in the UDMF public data channel. ```ts + import { BusinessError } from '@ohos.base'; // Specify the type of the data channel whose data is to be queried. - let options = { - intention: UDMF.Intention.DATA_HUB + let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB }; - + try { - UDMF.queryData(options, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in querying data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } - } - } else { - console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + unifiedDataChannel.queryData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in querying data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); + } } - }); + } + } else { + console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + } + }); } catch(e) { - console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); + let error: BusinessError = e as BusinessError; + console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `); } ``` diff --git a/en/application-dev/database/unified-data-definition.md b/en/application-dev/database/unified-data-definition.md index d0a3c100b5dadff7ef56a0938cde5b4d98b489d4..100029b135ef0e5b267f693c79c3aa9710084981 100644 --- a/en/application-dev/database/unified-data-definition.md +++ b/en/application-dev/database/unified-data-definition.md @@ -5,28 +5,35 @@ To streamline cross-application data interaction of OpenHarmony and minimize the application/service data interaction costs, the Unified Data Management Framework (UDMF) provides standard data definitions to define common data types. Applications can use the APIs provided by the UDMF to create and use these data types. +For example, in the cross-application drag scenario, the application of the drag source writes the data to be dragged to a [drag event](../reference/arkui-ts/ts-universal-events-drag-drop.md#dragevent) based on the standard data definitions. The application of the drop target reads the dragged data from the drag event and parses the data based on the standard data definitions. The data dragged between different applications complies with the same standard definitions, which avoids exhaustive data type adaptation and effectively reduces the development workload. ## Unified Data Types The UDMF provides the following unified data types: -**Basic data types**
Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types. +**Basic data types** + +Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types. **Figure 1** UDMF File ![UDMF_FILE](figures/udmf_type_File.png) -Figure 2 UDMF Text +**Figure 2** UDMF Text ![UDMF_TEXT](figures/udmf_type_Text.png) -**System Defined Types (SDTs)**
The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data. +**System Defined Types (SDTs)** + +The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data. **Figure 3** UDMF SDT data ![UDMF_SDT](figures/udmf_type_SDT.png) -**App Defined Type (ADT)**
The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem. +**App Defined Type (ADT)** + +The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem. **Figure 4** UDMF ADT data @@ -39,11 +46,11 @@ Figure 2 UDMF Text ## Available APIs -The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UnifiedDataType**. +The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UniformDataType**. -The following table describes common UDMF APIs. For more information, see [UDMF](../reference/apis/js-apis-data-udmf.md). +The following table describes common UDMF APIs. For more information about the APIs, see [Unified Data Channel](../reference/apis/js-apis-data-unifiedDataChannel.md) and [Standard Data Definition and Description](../reference/apis/js-apis-data-uniformTypeDescriptor.md). -| Class | API | Description | +| Class | API | Description | |---------------|-------------------|-----------------------------------------------------------------------------------------------| | UnifiedRecord | getType(): string | Obtains the data type of this data record.| | UnifiedData | constructor(record: UnifiedRecord) | A constructor used to create a **UnifiedData** object with a data record. | @@ -55,17 +62,19 @@ The following table describes common UDMF APIs. For more information, see [UDMF] The following describes how to create a **UnifiedData** object containing two data records: image and plain text. -1. Import the **@ohos.data.UDMF** module. +1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules. ```ts - import UDMF from '@ohos.data.UDMF'; + import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; + import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; ``` + 2. Create an image data record and initialize the **UnifiedData** object with the image data record. (1) Create an image data record. ```ts - let image = new UDMF.Image(); + let image = new unifiedDataChannel.Image(); ``` (2) Modify object attributes. @@ -84,12 +93,13 @@ The following describes how to create a **UnifiedData** object containing two da (4) Create a **UnifiedData** instance. ```ts - let unifiedData = new UDMF.UnifiedData(image); + let unifiedData = new unifiedDataChannel.UnifiedData(image); ``` -3. Create a plain text data record and add it to the **UnifiedData** instance created. +3. Create a plain text data record and add it to the **UnifiedData** instance created. + ```ts - let plainText = new UDMF.PlainText(); + let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'this is textContent of plainText'; plainText.abstract = 'abstract of plainText'; plainText.details = { @@ -98,25 +108,27 @@ The following describes how to create a **UnifiedData** object containing two da }; unifiedData.addRecord(plainText); ``` + 4. Obtain all data records in this **UnifiedData** instance. - + ```ts let records = unifiedData.getRecords(); ``` + 5. Traverse each record, determine the data type of the record, and convert the record into a child class object to obtain the original data record. - + ```ts for (let i = 0; i < records.length; i ++) { // Read the type of the data record. let type = records[i].getType(); switch (type) { - case UDMF.UnifiedDataType.IMAGE: + case uniformTypeDescriptor.UniformDataType.IMAGE: // Convert the data to obtain the original image data record. - let image = (records[i]); + let image = records[i] as unifiedDataChannel.Image; break; - case UDMF.UnifiedDataType.PLAIN_TEXT: + case uniformTypeDescriptor.UniformDataType.PLAIN_TEXT: // Convert the data to obtain the original text record. - let plainText = (records[i]); + let plainText = records[i] as unifiedDataChannel.PlainText; break; default: break; diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index e1f64b915980aa23b9c1154f435a500a34922938..2606d689eaceff514111f6d9b08d6d68265966c2 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -279,7 +279,8 @@ - [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md) - [@ohos.data.preferences (User Preferences)](js-apis-data-preferences.md) - [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md) - - [@ohos.data.UDMF (Unfied Data Management Framework)](js-apis-data-udmf.md) + - [@ohos.data.unifiedDataChannel (Unified Data Channel)](js-apis-data-unifiedDataChannel.md) + - [@ohos.data.uniformTypeDescriptor (Standard Data Definition)](js-apis-data-uniformTypeDescriptor.md) - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - File Management diff --git a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index 6691b47577dae3f00b30cda0b70b6725b5ea9495..a67d5dddcc2b862ff858d23ec70d0e16d7ab4161 100644 --- a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -4,11 +4,10 @@ The **DataShareExtensionAbility** module provides data share services based on t >**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 initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs provided by this module are system APIs. +> - The APIs provided by this module are system APIs and can be used only in the stage model. > -> The APIs of this module can be used only in the stage model. ## Modules to Import @@ -21,7 +20,7 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | context10+ | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|DataShareExtensionAbility context, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).| @@ -50,17 +49,17 @@ let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - onCreate(want, callback) { + onCreate(want: Want, callback: Function) { rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 - }, function (err, data) { + }, (err, data) => { console.info(`getRdbStore done, data : ${data}`); rdbStore = data; - rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { + rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { console.error(`executeSql done, error message : ${err}`); }); if (callback) { @@ -91,21 +90,22 @@ Inserts data into the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - insert(uri, valueBucket, callback) { + insert(uri: string, valueBucket: ValuesBucket, callback: Function) { if (valueBucket === null) { console.error('invalid valueBuckets'); return; } - rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) { + rdbStore.insert(TBL_NAME, valueBucket, (err, ret) => { console.info(`callback ret: ${ret}`); if (callback !== undefined) { callback(err, ret); @@ -136,20 +136,22 @@ Updates data in the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - update(uri, predicates, valueBucket, callback) { + update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: Function) { if (predicates === null || predicates === undefined) { return; } - rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) { + rdbStore.update(TBL_NAME, valueBucket, predicates, (err, ret) => { if (callback !== undefined) { callback(err, ret); } @@ -178,20 +180,21 @@ Deletes data from the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - delete(uri, predicates, callback) { + delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: Function) { if (predicates === null || predicates === undefined) { return; } - rdbStore.delete(TBL_NAME, predicates, function (err, ret) { + rdbStore.delete(TBL_NAME, predicates, (err, ret) => { if (callback !== undefined) { callback(err, ret); } @@ -221,20 +224,21 @@ Queries data from the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - query(uri, predicates, columns, callback) { + query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) { if (predicates === null || predicates === undefined) { return; } - rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { + rdbStore.query(TBL_NAME, predicates, columns, (err, resultSet) => { if (resultSet !== undefined) { console.info(`resultSet.rowCount: ${resultSet.rowCount}`); } @@ -266,21 +270,22 @@ Batch inserts data into the database. This API is called by the server and can b ```ts import rdb from '@ohos.data.relationalStore'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - batchInsert(uri, valueBuckets, callback) { + batchInsert(uri: string, valueBuckets: Array, callback: Function) { if (valueBuckets === null || valueBuckets.length === undefined) { console.error('invalid valueBuckets'); return; } - rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) { + rdbStore.batchInsert(TBL_NAME, valueBuckets, (err, ret) => { if (callback !== undefined) { callback(err, ret); } @@ -308,11 +313,17 @@ Normalizes a URI. This API can be overridden as required. ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - normalizeUri(uri, callback) { - let err = {'code':0}; - let ret = `normalize: ${uri}`; - callback(err, ret); - } + normalizeUri(uri: string, callback: Function) { + let key = 'code'; + let value = 0; + let err: BusinessError = { + code: value, + name: key, + message: key + }; + let ret: string = `normalize: ${uri}`; + callback(err, ret); + } }; ``` @@ -335,10 +346,16 @@ Denormalizes a URI. This API can be overridden as required. ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - denormalizeUri(uri, callback) { - let err = {'code':0}; - let ret = `denormalize ${uri}`; - callback(err, ret); - } + denormalizeUri(uri: string, callback: Function) { + let key = 'code'; + let value = 0; + let err: BusinessError = { + code: value, + name: key, + message: key + }; + let ret = `denormalize ${uri}`; + callback(err, ret); + } }; ``` diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 020d8c43c94ccb8313a7cde1fbad39048b11395b..c03275a33751dffc03d248de48196e36afc442cd 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -4,9 +4,9 @@ The **DataShareResultSet** module provides APIs for accessing the result set obt > **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 initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs provided by this module are system APIs. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -22,8 +22,9 @@ You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShar ```ts import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates' +import { BusinessError } from '@ohos.base' -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); await dataShare.createDataShareHelper(this.context, uri, (err, data) => { if (err != undefined) { @@ -36,12 +37,12 @@ await dataShare.createDataShareHelper(this.context, uri, (err, data) => { let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); -let resultSet; +let resultSet: DataShareResultSet; da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns).then((data) => { +dataShareHelper.query(uri, da, columns).then((data: DataShareResultSet) => { console.info("query end, data : " + data); resultSet = data; -}).catch((err) => { +}).catch((err: BusinessError) => { console.error("query fail, error message : " + err); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index ca246201a8d8be7c028f898307008bc69957a638..35c95cf2e3bcf806b9fb5bdd710eeaa5203057d3 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -51,7 +51,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; try { dataShare.createDataShareHelper(this.context, uri, (err, data) => { if (err !== undefined) { @@ -100,7 +100,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; try { dataShare.createDataShareHelper(this.context, uri, {isProxy : true}, (err, data) => { if (err !== undefined) { @@ -153,14 +153,15 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; try { - dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data) => { + dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data: dataShare.DataShareHelper) => { console.info("createDataShareHelper succeed, data : " + data); dataShareHelper = data; - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -268,7 +269,8 @@ Subscribes to changes of the specified data. After an observer is registered, th **Example** ```ts -function onCallback() { +let dataShareHelper: dataShare.DataShareHelper; +let onCallback: () => void = (): void => { console.info("**** Observer on callback ****"); } let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -294,8 +296,9 @@ Unsubscribes from data changes. **Example** ```ts -function callback() { - console.info("**** Observer callback ****"); +let dataShareHelper: dataShare.DataShareHelper; +let callback: () => void = (): void => { + console.info("**** Observer on callback ****"); } let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.on("dataChange", uri, callback); @@ -329,12 +332,17 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err **Example** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); let subscriberId = '11'; -let template = { +let key1: string = "p1"; +let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; +let key2: string = "p2"; +let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; +let template: dataShare.Template = { predicates : { - "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true", - "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false", + key1 : value1, + key2 : value2, }, scheduler : "select remindTimer(time) from TBL00" } @@ -367,12 +375,17 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err **Example** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); let subscriberId = '11'; -let template = { +let key1: string = "p1"; +let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; +let key2: string = "p2"; +let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; +let template: dataShare.Template = { predicates : { - "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true", - "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false", + key1 : value1, + key2 : value2, }, scheduler : "select remindTimer(time) from TBL00" } @@ -406,7 +419,10 @@ Subscribes to the changes of the data corresponding to the specified URI and tem **Example** ```ts -function onCallback(err, node:dataShare.RdbDataChangeNode) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let onCallback: (err: BusinessError, node: dataShare.RdbDataChangeNode) => void = (err: BusinessError, node:dataShare.RdbDataChangeNode): void => { console.info("onCallback " + JSON.stringify(node.uri)); console.info("onCallback " + JSON.stringify(node.templateId)); console.info("onCallback " + node.data.length); @@ -446,6 +462,7 @@ Unsubscribes from the changes of the data corresponding to the specified URI and **Example** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; let result:Array = dataShareHelper.off("rdbDataChange", [uri], templateId); @@ -477,7 +494,10 @@ Subscribes to the changes of the published data. **Example** ```ts -function onPublishCallback(err, node:dataShare.PublishedDataChangeNode) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let onPublishCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName)); console.info("onPublishCallback node data size" + node.data.length); for (let i = 0; i < node.data.length; i++) { @@ -521,7 +541,10 @@ Unsubscribes from the changes of the published data. **Example** ```ts -function offCallback(err, node:dataShare.PublishedDataChangeNode) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let offCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { console.info("**** Observer off callback ****"); } let uris:Array = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"]; @@ -557,10 +580,13 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err **Example** ```ts +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let arrayBuffer = new ArrayBuffer(1); let version = 1; let dataArray : Array = [{key:"key2", subscriberId:"11", data:arrayBuffer}]; -function publishCallback(err, result: Array) { +let publishCallback: (err: BusinessError, result: Array) => void = (err: BusinessError, result: Array): void => { console.info("publishCallback " + JSON.stringify(result)); } try { @@ -598,7 +624,10 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err | 15700012 | The data area is not exist.| ```ts -function publishCallback(err, result: Array) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let publishCallback: (err: BusinessError, result: Array) => void = (err: BusinessError, result: Array): void => { console.info("publishCallback " + JSON.stringify(result)); } let dataArray : Array = [ @@ -641,11 +670,12 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err **Example** ```ts -let dataArray : Array = [ +let dataShareHelper: dataShare.DataShareHelper; +let dataArray: Array = [ {key:"city", subscriberId:"11", data:"xian"}, {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, {key:"empty", subscriberId:"11", data:"nobody sub"}]; -let result: Array = dataShareHelper.publish(dataArray, "com.acts.ohos.data.datasharetest"); +let result: Promise> = dataShareHelper.publish(dataArray, "com.acts.ohos.data.datasharetest"); ``` ### getPublishedData10+ @@ -674,7 +704,10 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err **Example** ```ts -function publishCallback(err, data: Array) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let publishCallback: (err: BusinessError, data: Array) => void = (err: BusinessError, result: Array): void => { console.info("**** Observer publish callback ****"); } dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest", publishCallback); @@ -711,7 +744,8 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err **Example** ```ts -let publishedData:Array = dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest"); +let dataShareHelper: dataShare.DataShareHelper; +let publishedData: Promise> = dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest"); ``` ### insert @@ -733,11 +767,20 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Example** ```ts +import { ValuesBucket } from '@ohos.data.ValuesBucket' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -const valueBucket = { - "name": "rose", - "age": 22, - "salary": 200.5, +let key1: string = "name"; +let value1: string = "rose"; +let key2: string = "age"; +let value2: number = 22; +let key3: string = "salary"; +let value3: number = 200.5; +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { dataShareHelper.insert(uri, valueBucket, (err, data) => { @@ -776,16 +819,26 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** ```ts +import { BusinessError } from '@ohos.base' +import { ValuesBucket } from '@ohos.data.ValuesBucket' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -const valueBucket = { - "name": "rose1", - "age": 221, - "salary": 20.5, +let key1: string = "name"; +let value1: string = "rose1"; +let key2: string = "age"; +let value2: number = 21; +let key3: string = "salary"; +let value3: number = 20.5; +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { - dataShareHelper.insert(uri, valueBucket).then((data) => { + dataShareHelper.insert(uri, valueBucket).then((data: number) => { console.info("insert succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`insert error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -814,6 +867,7 @@ Deletes one or more data records from the database. This API uses an asynchronou ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); @@ -855,14 +909,16 @@ Deletes one or more data records from the database. This API uses a promise to r ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { BusinessError } from '@ohos.base' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); try { - dataShareHelper.delete(uri, da).then((data) => { + dataShareHelper.delete(uri, da).then((data: number) => { console.info("delete succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`delete error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -892,6 +948,7 @@ Queries data in the database. This API uses an asynchronous callback to return t ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); @@ -935,15 +992,17 @@ Queries data in the database. This API uses a promise to return the result. ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { BusinessError } from '@ohos.base' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); try { - dataShareHelper.query(uri, da, columns).then((data) => { + dataShareHelper.query(uri, da, columns).then((data: DataShareResultSet) => { console.info("query succeed, rowCount : " + data.rowCount); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`query error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -972,15 +1031,22 @@ Updates data in the database. This API uses an asynchronous callback to return t ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - +let key1: string = "name"; +let value1: string = "roe1" +let key2: string = "age"; +let value2: number = 21 +let key3: string = "salary"; +let value3: number = 20.5; +const va: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { dataShareHelper.update(uri, da, va, (err, data) => { @@ -1021,20 +1087,28 @@ Updates data in the database. This API uses a promise to return the result. ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' +import { BusinessError } from '@ohos.base' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - +let key1: string = "name"; +let value1: string = "roe1" +let key2: string = "age"; +let value2: number = 21 +let key3: string = "salary"; +let value3: number = 20.5; +const va: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { - dataShareHelper.update(uri, da, va).then((data) => { + dataShareHelper.update(uri, da, va).then((data: number) => { console.info("update succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`update error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -1061,10 +1135,22 @@ Batch inserts data into the database. This API uses an asynchronous callback to **Example** ```ts +import { ValuesBucket } from '@ohos.data.ValuesBucket' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, - {"name": "roe12", "age": 21, "salary": 20.5,}, - {"name": "roe13", "age": 21, "salary": 20.5,}) +let key1: string = "name"; +let value11: string = "roe11" +let key2: string = "age"; +let value21: number = 21; +let key3: string = "salary"; +let value31: number = 20.5; +let valuesBucket1: ValuesBucket = { + key1: value11, + key2: value21, + key3: value31, +} +let vbs = new Array(valuesBucket1); try { dataShareHelper.batchInsert(uri, vbs, (err, data) => { if (err !== undefined) { @@ -1102,14 +1188,27 @@ Batch inserts data into the database. This API uses a promise to return the resu **Example** ```ts +import { ValuesBucket } from '@ohos.data.ValuesBucket' +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, - {"name": "roe12", "age": 21, "salary": 20.5,}, - {"name": "roe13", "age": 21, "salary": 20.5,}) +let key1: string = "name"; +let value11: string = "roe11" +let key2: string = "age"; +let value21: number = 21; +let key3: string = "salary"; +let value31: number = 20.5; +let valuesBucket1: ValuesBucket = { + key1: value11, + key2: value21, + key3: value31, +} +let vbs = new Array(valuesBucket1); try { - dataShareHelper.batchInsert(uri, vbs).then((data) => { + dataShareHelper.batchInsert(uri, vbs).then((data: number) => { console.info("batchInsert succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -1135,6 +1234,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { if (err !== undefined) { @@ -1168,10 +1268,13 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.normalizeUri(uri).then((data) => { +dataShareHelper.normalizeUri(uri).then((data: string) => { console.info("normalizeUri = " + data); -}).catch((err) => { +}).catch((err: BusinessError) => { console.info("normalizeUri failed, error message : " + err); }); ``` @@ -1194,6 +1297,7 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result. **Example** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { if (err !== undefined) { @@ -1227,10 +1331,13 @@ Denormalizes a URI. This API uses a promise to return the result. Silent access **Example** ```ts +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.denormalizeUri(uri).then((data) => { +dataShareHelper.denormalizeUri(uri).then((data: string) => { console.info("denormalizeUri = " + data); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error("denormalizeUri failed, error message : " + err); }); ``` @@ -1253,6 +1360,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Example** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.info("***** notifyChange *****"); @@ -1282,6 +1390,7 @@ Notifies the registered observer of data changes. This API uses a promise to ret **Example** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 8892f9ff2538ad00cebda30ba7b80fa3abf31641..d3c864e065c2b453937843a679dea971c071efb5 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -23,10 +23,10 @@ Creates a distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| - | source | object | Yes| Attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| source | object | Yes| Attributes of the distributed data object.| **Return value** @@ -42,10 +42,20 @@ FA model: // Import the module. import distributedObject from '@ohos.data.distributedDataObject'; import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; // Obtain the context. let context = featureAbility.getContext(); -// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. -let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DataObject = distributedObject.create(context, source); ``` Stage model: @@ -54,13 +64,23 @@ Stage model: // Import the module. import distributedObject from '@ohos.data.distributedDataObject'; import UIAbility from '@ohos.app.ability.UIAbility'; - -let g_object = null; - +import { BusinessError } from '@ohos.base'; +import window from '@ohos.window'; + +let g_object: distributedObject.DataObject = null; +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - // Create a distributed data object, which has attributes of the string, number, boolean, and object types. - g_object = distributedObject.create(this.context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); + onWindowStageCreate(windowStage: window.WindowStage) { + let source: sourceObject = { + name: "amy", + age:18, + isVis:false + } + g_object = distributedObject.create(this.context, source); } } ``` @@ -75,15 +95,15 @@ Creates a random session ID. **Return value** - | Type| Description| - | -------- | -------- | - | string | Session ID created.| +| Type| Description| +| -------- | -------- | +| string | Session ID created.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -let sessionId = distributedObject.genSessionId(); +let sessionId: string = distributedObject.genSessionId(); ``` ## SaveSuccessResponse9+ @@ -124,18 +144,18 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sessionId | string | Yes| ID of a distributed data object on a trusted network.| - | callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the session ID is successfully set.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | Yes| ID of a distributed data object on a trusted network.| +| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the session ID is successfully set.| **Error codes** For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). - | ID| Error Message| - | -------- | -------- | - | 15400001 | Create table failed.| +| ID| Error Message| +| -------- | -------- | +| 15400001 | Create table failed.| **Example** @@ -158,17 +178,17 @@ Exits all joined sessions. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.| **Error codes** For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). - | ID| Error Message| - | -------- | -------- | - | 15400001 | Create table failed.| +| ID| Error Message| +| -------- | -------- | +| 15400001 | Create table failed.| **Example** @@ -179,7 +199,7 @@ g_object.setSessionId(distributedObject.genSessionId(), ()=>{ }); // Exit the distributed network. g_object.setSessionId(() => { - console.info("leave all lession."); + console.info("leave all session."); }); ``` @@ -195,9 +215,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** @@ -209,9 +229,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). - | ID| Error Message| - | -------- | -------- | - | 15400001 | Create table failed.| +| ID| Error Message| +| -------- | -------- | +| 15400001 | Create table failed.| **Example** @@ -219,13 +239,13 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo // Add g_object to the distributed network. g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ console.info("join session."); - }).catch((error)=>{ + }).catch((error: BusinessError)=>{ console.info("error:" + error.code + error.message); }); // Exit the distributed network. g_object.setSessionId().then (()=>{ - console.info("leave all lession."); - }).catch((error)=>{ + console.info("leave all session."); + }).catch((error: BusinessError)=>{ console.info("error:" + error.code + error.message); }); ``` @@ -240,23 +260,26 @@ Subscribes to data changes of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js -globalThis.changeCallback = (sessionId, changeData) => { - console.info("change" + sessionId); - if (changeData != null && changeData != undefined) { - changeData.forEach(element => { - console.info("changed !" + element + " " + g_object[element]); - }); - } +interface ChangeCallback { + sessionId: string, + fields: Array } -g_object.on("change", globalThis.changeCallback); +g_object.on("change", (changeData: ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); ``` ### off('change')9+ @@ -269,17 +292,24 @@ Unsubscribes from the data changes of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js // Unregister the specified data change callback. -g_object.off("change", globalThis.changeCallback); +g_object.off("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); // Unregister all data change callbacks. g_object.off("change"); ``` @@ -294,18 +324,23 @@ Subscribes to status changes of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** ```js -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +interface onStatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' } -g_object.on("status", globalThis.statusCallback); + +g_object.on("status", (statusCallback:onStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); +}); ``` ### off('status')9+ @@ -318,20 +353,24 @@ Unsubscribes from the status change of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| +| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| **Example** ```js -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +interface offStatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' } // Unregister the specified status change callback. -g_object.off("status",globalThis.statusCallback); +g_object.off("status", (statusCallback:StatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); +}); // Unregister all status change callbacks. g_object.off("status"); ``` @@ -354,16 +393,16 @@ The saved data will be released in the following cases: **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| - | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| +| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** ```ts g_object.setSessionId("123456"); -g_object.save("local", (err, result) => { +g_object.save("local", (err: BusinessError, result:distributedObject.SaveSuccessResponse) => { if (err) { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); @@ -394,26 +433,26 @@ The saved data will be released in the following cases: **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Type| Description| +| -------- | -------- | +| Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** ```js g_object.setSessionId("123456"); -g_object.save("local").then((result) => { +g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => { console.info("save callback"); console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}).catch((err) => { +}).catch((err: BusinessError) => { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); }); @@ -432,16 +471,16 @@ If the object is stored on another device, the data on the local device will be **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** ```js g_object.setSessionId("123456"); // Save data for persistence. -g_object.save("local", (err, result) => { +g_object.save("local", (err: BusinessError, result: distributedObject.SaveSuccessResponse) => { if (err) { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); @@ -453,7 +492,7 @@ g_object.save("local", (err, result) => { console.info("save deviceId: " + result.deviceId); }); // Delete the persistence data. -g_object.revokeSave((err, result) => { +g_object.revokeSave((err: BusinessError, result: distributedObject.RevokeSaveSuccessResponse) => { if (err) { console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error message: " + err.message); @@ -477,29 +516,29 @@ If the object is stored on another device, the data on the local device will be **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Type| Description| +| -------- | -------- | +| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** ```ts g_object.setSessionId("123456"); -// Save data for persistence. -g_object.save("local").then((result) => { +// Save data for persistence. +g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => { console.info("save callback"); console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}).catch((err) => { +}).catch((err: BusinessError) => { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); }); // Delete the persistence data. -g_object.revokeSave().then((result) => { +g_object.revokeSave().then((result: distributedObject.RevokeSaveSuccessResponse) => { console.info("revokeSave callback"); console.info("sessionId" + result.sessionId); -}).catch((err)=> { +}).catch((err: BusinessError)=> { console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error message = " + err.message); }); @@ -520,9 +559,9 @@ Creates a distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | source | object | Yes| Attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | object | Yes| Attributes of the distributed data object.| **Return value** @@ -534,8 +573,17 @@ Creates a distributed data object. ```js import distributedObject from '@ohos.data.distributedDataObject'; -// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); ``` ## DistributedObject(deprecated) @@ -558,21 +606,31 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); // Add g_object to the distributed network. g_object.setSessionId(distributedObject.genSessionId()); // Remove g_object from the distributed network. @@ -593,25 +651,38 @@ Subscribes to data changes of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); -globalThis.changeCallback = (sessionId, changeData) => { - console.info("change" + sessionId); - if (changeData != null && changeData != undefined) { - changeData.forEach(element => { - console.info("changed !" + element + " " + g_object[element]); - }); - } +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +interface ChangeCallback { + sessionId: string, + fields: Array } -g_object.on("change", globalThis.changeCallback); +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); +g_object.on("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); ``` ### off('change')(deprecated) @@ -628,19 +699,40 @@ Unsubscribes from the data changes of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +interface ChangeCallback { + sessionId: string, + fields: Array +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); // Unregister the specified data change callback. -g_object.off("change", globalThis.changeCallback); +g_object.off("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); // Unregister all data change callbacks. g_object.off("change"); ``` @@ -659,20 +751,36 @@ Subscribes to status changes of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; + +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +interface StatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false } -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); -g_object.on("status", globalThis.statusCallback); +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); + +g_object.on("status", (statusCallback:StatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); +}); ``` ### off('status')(deprecated) @@ -689,8 +797,8 @@ Unsubscribes from the status change of this distributed data object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| @@ -699,12 +807,26 @@ Unsubscribes from the status change of this distributed data object. ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +interface offStatusCallback { + sessionId: string, + deviceId: string, + status: 'online' | 'offline' } +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); // Unregister the specified status change callback. -g_object.off("status",globalThis.statusCallback); +g_object.off("status", (statusCallback:offStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId); +}); // Unregister all status change callbacks. g_object.off("status"); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index bd89f5ba07d67232019b4e7b00ca9ae8c1ccdbdf..9c2d483b0273bb87984004825af0e30ecc5820ef 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -49,11 +49,13 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; + let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - data_preferences.getPreferences(context, 'mystore', function (err, val) { + data_preferences.getPreferences(context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -70,16 +72,18 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.getPreferences(this.context, 'mystore', function (err, val) { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { if (err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); - return; + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + return; } preferences = val; console.info("Succeeded in getting preferences."); @@ -119,15 +123,17 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - let promise = data_preferences.getPreferences(context, 'mystore'); - promise.then((object) => { + let promise = data_preferences.getPreferences(context, 'myStore'); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -139,17 +145,19 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.getPreferences(this.context, 'mystore'); - promise.then((object) => { + let promise = data_preferences.getPreferences(this.context, 'myStore'); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -191,11 +199,14 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - data_preferences.getPreferences(context, { name: 'mystore' }, function (err, val) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -213,13 +224,16 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, val) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -271,15 +285,17 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - let promise = data_preferences.getPreferences(context, { name: 'mystore' }); - promise.then((object) => { + let options: data_preferences.Options = { name: 'myStore' }; + let promise = data_preferences.getPreferences(context, options); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -291,17 +307,20 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }); - promise.then((object) => { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.getPreferences(this.context, options); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -311,7 +330,6 @@ class EntryAbility extends UIAbility { } ``` - ## data_preferences.deletePreferences deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void @@ -345,10 +363,12 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - data_preferences.deletePreferences(context, 'mystore', function (err) { + data_preferences.deletePreferences(context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -364,11 +384,13 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.deletePreferences(this.context, 'mystore', function (err) { + data_preferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -420,13 +442,15 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - let promise = data_preferences.deletePreferences(context, 'mystore'); + let promise = data_preferences.deletePreferences(context, 'myStore'); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -438,14 +462,16 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try{ - let promise = data_preferences.deletePreferences(this.context, 'mystore'); + let promise = data_preferences.deletePreferences(this.context, 'myStore'); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -490,10 +516,13 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - data_preferences.deletePreferences(context, { name: 'mystore' }, function (err) { + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.deletePreferences(context, options, (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -509,11 +538,14 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.deletePreferences(this.context, options, (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -568,13 +600,16 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - let promise = data_preferences.deletePreferences(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + let promise = data_preferences.deletePreferences(context, options); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -586,14 +621,17 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try{ - let promise = data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.deletePreferences(this.context, options); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -631,9 +669,11 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { + data_preferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -649,11 +689,13 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { + data_preferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -699,12 +741,14 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); + let promise = data_preferences.removePreferencesFromCache(context, 'myStore'); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -716,14 +760,16 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore'); + let promise = data_preferences.removePreferencesFromCache(this.context, 'myStore'); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -761,7 +807,7 @@ FA model: import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCacheSync(context, 'mystore'); + data_preferences.removePreferencesFromCacheSync(context, 'myStore'); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -773,9 +819,9 @@ Stage model: import UIAbility from '@ohos.app.ability.UIAbility'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCacheSync(this.context, 'mystore'); + data_preferences.removePreferencesFromCacheSync(this.context, 'myStore'); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -819,9 +865,11 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCache(context, { name: 'mystore' }, function (err) { + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.removePreferencesFromCache(context, options, (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -837,11 +885,14 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -896,12 +947,14 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); try { - let promise = data_preferences.removePreferencesFromCache(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + let promise = data_preferences.removePreferencesFromCache(context, options); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -913,14 +966,17 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.removePreferencesFromCache(this.context, options); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -928,10 +984,6 @@ class EntryAbility extends UIAbility { } } } -``` - } - } -} ``` ## Options10+ @@ -972,7 +1024,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ```js try { - preferences.get('startup', 'default', function (err, val) { + preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => { if (err) { console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1011,9 +1063,9 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ```js try { let promise = preferences.get('startup', 'default'); - promise.then((data) => { + promise.then((data: data_preferences.ValueType) => { console.info("Got the value of 'startup'. Data: " + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -1046,7 +1098,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ```js try { - let value = preferences.getSync('startup', 'default'); + let value: data_preferences.ValueType = preferences.getSync('startup', 'default'); console.info("Succeeded in getting value of 'startup'. Data: " + value); } catch(err) { console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); @@ -1071,14 +1123,14 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an ```js try { - preferences.getAll(function (err, value) { + preferences.getAll((err: BusinessError, value: data_preferences.ValueType) => { if (err) { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); return; } - let allKeys = Object.keys(value); - console.info("getAll keys = " + allKeys); - console.info("getAll object = " + JSON.stringify(value)); + let allKeys = Object.keys(value); + console.info("getAll keys = " + allKeys); + console.info("getAll object = " + JSON.stringify(value)); }) } catch (err) { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); @@ -1105,11 +1157,11 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses a p ```js try { let promise = preferences.getAll(); - promise.then((value) => { + promise.then((value: data_preferences.ValueType) => { let allKeys = Object.keys(value); console.info('getAll keys = ' + allKeys); console.info("getAll object = " + JSON.stringify(value)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); }) } catch (err) { @@ -1164,7 +1216,7 @@ Writes data to the cached **Preferences** instance. This API uses an asynchronou ```js try { - preferences.put('startup', 'auto', function (err) { + preferences.put('startup', 'auto', (err: BusinessError) => { if (err) { console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1205,7 +1257,7 @@ try { let promise = preferences.put('startup', 'auto'); promise.then(() => { console.info("Successfully put the value of 'startup'."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); }) } catch(err) { @@ -1259,7 +1311,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g ```js try { - preferences.has('startup', function (err, val) { + preferences.has('startup', (err: BusinessError, val: boolean) => { if (err) { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1269,7 +1321,7 @@ try { } else { console.info("The key 'startup' is not contained."); } - }) + }) } catch (err) { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); } @@ -1301,15 +1353,15 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g ```js try { let promise = preferences.has('startup'); - promise.then((val) => { + promise.then((val: boolean) => { if (val) { console.info("The key 'startup' is contained."); } else { console.info("The key 'startup' is not contained."); } - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); - }) + }) } catch(err) { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); } @@ -1340,7 +1392,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g ```js try { - let isExist = preferences.hasSync('startup'); + let isExist: boolean = preferences.hasSync('startup'); if (isExist) { console.info("The key 'startup' is contained."); } else { @@ -1371,7 +1423,7 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie ```js try { - preferences.delete('startup', function (err) { + preferences.delete('startup', (err: BusinessError) => { if (err) { console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1411,7 +1463,7 @@ try { let promise = preferences.delete('startup'); promise.then(() => { console.info("Deleted the key 'startup'."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); }) } catch(err) { @@ -1463,7 +1515,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file. ```js try { - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. code =" + err.code + ", message =" + err.message); return; @@ -1497,7 +1549,7 @@ try { let promise = preferences.flush(); promise.then(() => { console.info("Successfully flushed data."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to flush. code =" + err.code + ", message =" + err.message); }) } catch (err) { @@ -1524,7 +1576,7 @@ Clears all data in the cached **Preferences** instance. This API uses an asynchr ```js try { - preferences.clear(function (err) { + preferences.clear((err: BusinessError) =>{ if (err) { console.error("Failed to clear. code =" + err.code + ", message =" + err.message); return; @@ -1558,7 +1610,7 @@ try { let promise = preferences.clear(); promise.then(() => { console.info("Successfully cleared data."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to clear. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -1604,29 +1656,31 @@ Subscribes to data changes. A callback will be triggered to return the new value **Example** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('change', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('change', observer); - preferences.put('startup', 'manual', function (err) { + }); + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { - console.error("Failed to put the value of 'startup'. Cause: " + err); - return; + console.error("Failed to put the value of 'startup'. Cause: " + err); + return; } console.info("Successfully put the value of 'startup'."); - preferences.flush(function (err) { - if (err) { - console.error("Failed to flush. Cause: " + err); - return; - } - console.info("Successfully flushed data."); + preferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Successfully flushed data."); }) }) }) @@ -1663,24 +1717,26 @@ For details about the error codes, see [User Preference Error Codes](../errorcod **Example 1** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('multiProcessChange', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('multiProcessChange', observer); - preferences.put('startup', 'manual', function (err) { + }); + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Successfully put the value of 'startup'."); - - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. Cause: " + err); return; @@ -1697,17 +1753,21 @@ try { **Example 2** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) { + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } preferences = val; - let observer = function (key) { + preferences.on('multiProcessChange', (key: observer) => { console.info("The key " + key + " changed."); try { - data_preferences.removePreferencesFromCache(this.context, { name: 'mystore' }, function (err) { + data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -1720,7 +1780,7 @@ try { } try { - data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) { + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -1731,16 +1791,15 @@ try { } catch (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); } - } - preferences.on('multiProcessChange', observer); - preferences.put('startup', 'manual', function (err) { + }); + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Successfully put the value of 'startup'."); - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. Cause: " + err); return; @@ -1772,31 +1831,35 @@ Unsubscribes from data changes. **Example** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('change', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { + }); + preferences.put('startup', 'auto', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Successfully put the value of 'startup'."); - preferences.flush(function (err) { + preferences.flush((err: BusinessError) =>{ if (err) { console.error("Failed to flush. Cause: " + err); return; } console.info("Successfully flushed data."); }) - preferences.off('change', observer); + preferences.off('change', (key: observer) => { + console.info("The key " + key + " changed."); + }); }) }) } catch (err) { @@ -1822,31 +1885,36 @@ Unsubscribes from inter-process data changes. **Example** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('multiProcessChange', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('multiProcessChange', observer); - preferences.put('startup', 'auto', function (err) { + }); + preferences.put('startup', 'auto', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Successfully put the value of 'startup'."); - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. Cause: " + err); return; } console.info("Successfully flushed data."); }) - preferences.off('multiProcessChange', observer); + preferences.off('multiProcessChange', (key: observer) => { + console.info("The key " + key + " changed."); + }); }) }) } catch (err) { 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 3c6f7aa5b9e2a554ecaeda593b1fbc394eea210e..08999042c6a8c14483b07ba0cb28dcdbca7b99f0 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -43,11 +43,11 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db"} -data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { +data_rdb.getRdbStore(context, STORE_CONFIG, 1, (err, rdbStore) => { if (err) { console.info("Failed to get RdbStore, err: " + err) return @@ -61,23 +61,26 @@ Stage model: ```ts // Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from "@ohos.base"; +import window from '@ohos.window'; -let context; -class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } +let context: Context; +interface storeConfig { + name: string } -// Call getRdbStore. -const STORE_CONFIG = { name: "RdbTest.db"} -data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { - if (err) { +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage){ + let STORE_CONFIG: storeConfig = { name: "RdbTest.db"}; + data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, (err: BusinessError, rdbStore: data_rdb.RdbStore) => { + if (err) { console.info("Failed to get RdbStore, err: " + err) return - } - console.log("Got RdbStore successfully.") -}) + } + console.log("Got RdbStore successfully.") + }) + } +} ``` ## data_rdb.getRdbStore @@ -109,7 +112,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db" } @@ -126,21 +129,26 @@ Stage model: ```ts // Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from "@ohos.base"; +import window from '@ohos.window'; -let context; +let context: Context; +interface storeConfig { + name: string +} class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } + onWindowStageCreate(windowStage: window.WindowStage){ + context = this.context + } } // Call getRdbStore. -const STORE_CONFIG = { name: "RdbTest.db" } +let STORE_CONFIG: storeConfig = { name: "RdbTest.db"}; let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1); -promise.then(async (rdbStore) => { - console.log("Got RdbStore successfully.") -}).catch((err) => { - console.log("Failed to get RdbStore, err: " + err) +promise.then(async (rdbStore: data_rdb.RdbStore) => { + console.log("Got RdbStore successfully.") +}).catch((err: BusinessError) => { + console.log("Failed to get RdbStore, err: " + err) }) ``` @@ -167,15 +175,15 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // Call deleteRdbStore. -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Failed to delete RdbStore, err: " + err) - return - } - console.log("Deleted RdbStore successfully.") +data_rdb.deleteRdbStore(context, "RdbTest.db", (err) => { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") }) ``` @@ -184,21 +192,22 @@ Stage model: ```ts // Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; -let context; +let context: Context; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } + onWindowStageCreate(windowStage: window.WindowStage){ + context = this.context + } } // Call deleteRdbStore. -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Failed to delete RdbStore, err: " + err) - return - } - console.log("Deleted RdbStore successfully.") +data_rdb.deleteRdbStore(context, "RdbTest.db", (err) => { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") }) ``` @@ -230,7 +239,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // Call deleteRdbStore. let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") @@ -246,20 +255,22 @@ Stage model: ```ts // Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from "@ohos.base"; +import window from '@ohos.window'; -let context; +let context: Context; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } + onWindowStageCreate(windowStage: window.WindowStage){ + context = this.context + } } // Call deleteRdbStore. let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") promise.then(()=>{ - console.log("Deleted RdbStore successfully.") -}).catch((err) => { - console.info("Failed to delete RdbStore, err: " + err) + console.log("Deleted RdbStore successfully.") +}).catch((err: BusinessError) => { + console.info("Failed to delete RdbStore, err: " + err) }) ``` @@ -371,8 +382,8 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceIds = []; +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -381,7 +392,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } }) diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md index 8d30126fec7cf31a42a9ae3bacf5d66db8b83238..87790f1020aa6aeeb3ee174f986a19666cdef20f 100644 --- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -15,7 +15,7 @@ The **relationalStore** module provides the following functions: ## Modules to Import ```js -import relationalStore from '@ohos.data.relationalStore' +import relationalStore from '@ohos.data.relationalStore'; ``` ## relationalStore.getRdbStore @@ -52,19 +52,20 @@ FA model: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; // Obtain the context. let context = featureAbility.getContext(); -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => { store = rdbStore; if (err) { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); @@ -77,17 +78,19 @@ relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { Stage model: ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - var store; - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage) { + let store: relationalStore.RdbStore; + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; - relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => { store = rdbStore; if (err) { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); @@ -137,23 +140,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; // Obtain the context. let context = featureAbility.getContext(); -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -let promise = relationalStore.getRdbStore(context, STORE_CONFIG); -promise.then(async (rdbStore) => { +let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG); +promise.then(async (rdbStore: relationalStore.RdbStore) => { store = rdbStore; - console.info(`Get RdbStore successfully.`); -}).catch((err) => { + console.info(`Get RdbStore successfully.`) +}).catch((err: BusinessError) => { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -161,21 +165,23 @@ promise.then(async (rdbStore) => { Stage model: ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - var store; - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage) { + let store: relationalStore.RdbStore; + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; - + let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG); - promise.then(async (rdbStore) => { + promise.then(async (rdbStore: relationalStore.RdbStore) => { store = rdbStore; console.info(`Get RdbStore successfully.`) - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) } @@ -214,14 +220,15 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; // Obtain the context. let context = featureAbility.getContext() -relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) { +relationalStore.deleteRdbStore(this.context, "RdbTest.db", (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -234,13 +241,15 @@ relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) { Stage model: ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) { + onWindowStageCreate(windowStage: window.WindowStage){ + relationalStore.deleteRdbStore(this.context, "RdbTest.db", (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -289,18 +298,19 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; // Obtain the context. let context = featureAbility.getContext(); -let promise = relationalStore.deleteRdbStore(context, "RdbTest.db"); +let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -308,17 +318,19 @@ promise.then(()=>{ Stage model: ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ + onWindowStageCreate(windowStage: window.WindowStage){ let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) } @@ -359,18 +371,19 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; // Obtain the context. let context = featureAbility.getContext() -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.deleteRdbStore(context, STORE_CONFIG, function (err) { +relationalStore.deleteRdbStore(this.context, STORE_CONFIG, (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -383,17 +396,19 @@ relationalStore.deleteRdbStore(context, STORE_CONFIG, function (err) { Stage model: ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage){ + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; - relationalStore.deleteRdbStore(this.context, STORE_CONFIG, function (err) { + relationalStore.deleteRdbStore(this.context, STORE_CONFIG, (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -444,22 +459,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; // Obtain the context. let context = featureAbility.getContext(); -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -let promise = relationalStore.deleteRdbStore(context, STORE_CONFIG); +let promise = relationalStore.deleteRdbStore(this.context, STORE_CONFIG); promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -467,13 +483,15 @@ promise.then(()=>{ Stage model: ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage){ + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; @@ -481,7 +499,7 @@ class EntryAbility extends UIAbility { promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) } @@ -577,23 +595,25 @@ Defines the data types allowed. ## ValuesBucket -Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. +Enumerates the types of the key in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Key Type| Value Type | | ------ | ----------------------- | -| string | [ValueType](#valuetype) | +| number | The primary key is a number.| +| string | The primary key is a string.| ## PRIKeyType10+ -Represents the type of the primary key in a row of a database table. +Enumerates the types of the primary key in a row of a database table. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Type | Description | | ---------------- | ---------------------------------- | -| number \| string | The type of the primary key can be number or string.| +| number | The primary key is a number.| +| string | The primary key is a string.| ## UTCTime10+ @@ -798,7 +818,8 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ > **NOTE** > -> The value of **devices** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **devices** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). +If **inDevices** is specified in **predicates** when **sync()** is called, data is synchronized with the specified device. If **inDevices** is not specified, data is synchronized with all devices on the network by default. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -817,22 +838,20 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceIds = []; +import deviceManager from '@ohos.distributedDeviceManager'; +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; + +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + for (let i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; + } +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } -}) - let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.inDevices(deviceIds); ``` @@ -844,6 +863,7 @@ inAllDevices(): RdbPredicates Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** @@ -1639,6 +1659,7 @@ Before using the APIs of this class, use [executeSql](#executesql) to initialize **Example** ```js +let store: relationalStore.RdbStore; // Set the RDB store version. store.version = 3; // Obtain the RDB store version. @@ -1673,13 +1694,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -store.insert("EMPLOYEE", valueBucket, function (err, rowId) { +store.insert("EMPLOYEE", valueBucket, (err, rowId) => { if (err) { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); return; @@ -1717,13 +1748,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rowId) { +store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rowId) => { if (err) { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); return; @@ -1765,16 +1806,27 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +import { BusinessError } from "@ohos.base"; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let promise = store.insert("EMPLOYEE", valueBucket); -promise.then((rowId) => { +promise.then((rowId: number) => { console.info(`Insert is successful, rowId = ${rowId}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1813,16 +1865,27 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +import { BusinessError } from "@ohos.base"; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let promise = store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); -promise.then((rowId) => { +promise.then((rowId: number) => { console.info(`Insert is successful, rowId = ${rowId}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1855,27 +1918,45 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); +const valueBucket1: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) +const valueBucket2: ValuesBucket = { + key1: value5, + key2: value6, + key3: value7, + key4: value8, }; -const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) +const valueBucket3: ValuesBucket = { + key1: value9, + key2: value10, + key3: value11, + key4: value12, }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -store.batchInsert("EMPLOYEE", valueBuckets, function(err, insertNum) { +store.batchInsert("EMPLOYEE", valueBuckets, (err, insertNum) => { if (err) { console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); return; @@ -1917,30 +1998,49 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +import { BusinessError } from "@ohos.base"; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); +const valueBucket1: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) +const valueBucket2: ValuesBucket = { + key1: value5, + key2: value6, + key3: value7, + key4: value8, }; -const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) +const valueBucket3: ValuesBucket = { + key1: value9, + key2: value10, + key3: value11, + key4: value12, }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); let promise = store.batchInsert("EMPLOYEE", valueBuckets); -promise.then((insertNum) => { +promise.then((insertNum: number) => { console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1973,11 +2073,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); @@ -2019,15 +2129,25 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { +store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rows) => { if (err) { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); return; @@ -2069,18 +2189,29 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +import { BusinessError } from "@ohos.base"; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); let promise = store.update(valueBucket, predicates); -promise.then(async (rows) => { +promise.then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2119,18 +2250,29 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +import { BusinessError } from "@ohos.base"; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); let promise = store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); -promise.then(async (rows) => { +promise.then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2169,15 +2311,25 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); -store.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { +store.update("EMPLOYEE", valueBucket, predicates, (err, rows) => { if (err) { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); return; @@ -2224,19 +2376,30 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +import { BusinessError } from "@ohos.base"; + +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); let promise = store.update("EMPLOYEE", valueBucket, predicates); -promise.then(async (rows) => { +promise.then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2270,7 +2433,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -store.delete(predicates, function (err, rows) { +store.delete(predicates, (err, rows) => { if (err) { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); return; @@ -2311,12 +2474,14 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); let promise = store.delete(predicates); -promise.then((rows) => { +promise.then((rows: Number) => { console.info(`Delete rows: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2356,7 +2521,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); -store.delete("EMPLOYEE", predicates, function (err, rows) { +store.delete("EMPLOYEE", predicates, (err, rows) => { if (err) { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); return; @@ -2402,13 +2567,15 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { BusinessError } from "@ohos.base"; + let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); let promise = store.delete("EMPLOYEE", predicates); -promise.then((rows) => { +promise.then((rows: Number) => { console.info(`Delete rows: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2441,7 +2608,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -store.query(predicates, function (err, resultSet) { +store.query(predicates, (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2489,7 +2656,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2539,11 +2706,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** - ```js +```js +import { BusinessError } from "@ohos.base"; + let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. while (resultSet.goToNextRow()) { @@ -2555,10 +2724,10 @@ promise.then((resultSet) => { } // Release the dataset memory. resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) - ``` +``` ### query10+ @@ -2594,7 +2763,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Rose"); -store.query("EMPLOYEE", predicates, function (err, resultSet) { +store.query("EMPLOYEE", predicates, (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2648,7 +2817,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Rose"); -store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2704,11 +2873,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { BusinessError } from "@ohos.base"; + let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Rose"); let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. while (resultSet.goToNextRow()) { @@ -2720,7 +2891,7 @@ promise.then((resultSet) => { } // Release the dataset memory. resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2733,7 +2904,7 @@ Queries data from the RDB store of a remote device based on specified conditions > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2758,41 +2929,38 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceId = null; +import deviceManager from '@ohos.distributedDeviceManager'; +import { BusinessError } from "@ohos.base"; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; + +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); -store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet) { - if (err) { - console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); - return; - } - console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); - // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. - while (resultSet.goToNextRow()) { - const id = resultSet.getLong(resultSet.getColumnIndex("ID")); - const name = resultSet.getString(resultSet.getColumnIndex("NAME")); - const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); - const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); - console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); - } - // Release the dataset memory. - resultSet.close(); +let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet: relationalStore.ResultSet) => { + console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. + while (resultSet.goToNextRow()) { + const id = resultSet.getLong(resultSet.getColumnIndex("ID")); + const name = resultSet.getString(resultSet.getColumnIndex("NAME")); + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); } -) + // Release the dataset memory. + resultSet.close(); +}).catch((err: BusinessError) => { + console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); +}) ``` ### remoteQuery @@ -2803,7 +2971,7 @@ Queries data from the RDB store of a remote device based on specified conditions > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2833,24 +3001,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceId = null; +import deviceManager from '@ohos.distributedDeviceManager'; +import { BusinessError } from "@ohos.base"; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; + +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. while (resultSet.goToNextRow()) { @@ -2862,7 +3030,7 @@ promise.then((resultSet) => { } // Release the dataset memory. resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); }) ``` @@ -2893,7 +3061,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", function (err, resultSet) { +store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2939,7 +3107,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { +store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2990,8 +3158,10 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'"); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. while (resultSet.goToNextRow()) { @@ -3003,7 +3173,7 @@ promise.then((resultSet) => { } // Release the dataset memory. resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3036,7 +3206,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" -store.executeSql(SQL_DELETE_TABLE, function(err) { +store.executeSql(SQL_DELETE_TABLE, (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); return; @@ -3074,7 +3244,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?" -store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], function(err) { +store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); return; @@ -3116,12 +3286,14 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" let promise = store.executeSql(SQL_DELETE_TABLE); promise.then(() => { - console.info(`Delete table done.`); -}).catch((err) => { - console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); + console.info(`Delete table done.`); +}).catch((err: BusinessError) => { + console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3154,12 +3326,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js let PRIKey = [1, 4, 2, 3]; -store.getModifyTime("cloud_tasks", "uuid", PRIKey, function (err, modifyTime) { - if (err) { - console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); - return; - } - let size = modifyTime.size(); +store.getModifyTime("cloud_tasks", "uuid", PRIKey, (err, modifyTime: relationalStore.ModifyTime)=> { + if (err) { + console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); + return; + } + let size = modifyTime.size; }); ``` @@ -3196,11 +3368,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + let PRIKey = [1, 2, 3]; -store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime) => { - let size = modifyTime.size(); -}).catch((err) => { - console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); +store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime: relationalStore.ModifyTime) => { + let size = modifyTime.size; +}).catch((err: BusinessError) => { + console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3225,22 +3399,32 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js import featureAbility from '@ohos.ability.featureAbility' +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + let context = featureAbility.getContext(); -const STORE_CONFIG = { +let key1 = "name"; +let key2 = "age"; +let key3 = "SALARY"; +let key4 = "blobType"; +let value1 = "Lisi"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3]); +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => { if (err) { console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } store.beginTransaction(); - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), + const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; await store.insert("test", valueBucket); store.commit(); @@ -3259,22 +3443,32 @@ Commits the executed SQL statements. ```js import featureAbility from '@ohos.ability.featureAbility' +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + let context = featureAbility.getContext(); -const STORE_CONFIG = { +let key1 = "name"; +let key2 = "age"; +let key3 = "SALARY"; +let key4 = "blobType"; +let value1 = "Lisi"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3]); +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => { if (err) { console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } store.beginTransaction(); - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), + const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; await store.insert("test", valueBucket); store.commit(); @@ -3293,25 +3487,34 @@ Rolls back the SQL statements that have been executed. ```js import featureAbility from '@ohos.ability.featureAbility' +import { ValuesBucket } from '@ohos.data.ValuesBucket'; + let context = featureAbility.getContext(); -const STORE_CONFIG = { +let key1 = "name"; +let key2 = "age"; +let key3 = "SALARY"; +let key4 = "blobType"; +let value1 = "Lisi"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3]); +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => { if (err) { console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } try { store.beginTransaction() - const valueBucket = { - "id": 1, - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - }; + const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + }; await store.insert("test", valueBucket); store.commit(); } catch (err) { @@ -3347,7 +3550,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -store.backup("dbBackup.db", function(err) { +store.backup("dbBackup.db", (err) => { if (err) { console.error(`Backup failed, code is ${err.code},message is ${err.message}`); return; @@ -3387,10 +3590,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + let promiseBackup = store.backup("dbBackup.db"); promiseBackup.then(()=>{ console.info(`Backup success.`); -}).catch((err)=>{ +}).catch((err: BusinessError)=>{ console.error(`Backup failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3421,7 +3626,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -store.restore("dbBackup.db", function(err) { +store.restore("dbBackup.db", (err) => { if (err) { console.error(`Restore failed, code is ${err.code},message is ${err.message}`); return; @@ -3461,10 +3666,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + let promiseRestore = store.restore("dbBackup.db"); promiseRestore.then(()=>{ console.info(`Restore success.`); -}).catch((err)=>{ +}).catch((err: BusinessError)=>{ console.error(`Restore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3497,7 +3704,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -store.setDistributedTables(["EMPLOYEE"], function (err) { +store.setDistributedTables(["EMPLOYEE"], (err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); return; @@ -3539,10 +3746,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + let promise = store.setDistributedTables(["EMPLOYEE"]); promise.then(() => { console.info(`SetDistributedTables successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3577,7 +3786,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, function (err) { +store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, (err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); return; @@ -3619,7 +3828,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ```js store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, { autoSync: true -}, function (err) { +},(err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); return; @@ -3664,12 +3873,14 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js +import { BusinessError } from "@ohos.base"; + let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, { autoSync: true }); promise.then(() => { console.info(`SetDistributedTables successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3682,7 +3893,7 @@ Obtains the distributed table name of a remote device based on the local table n > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3707,26 +3918,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceId = null; +import deviceManager from '@ohos.distributedDeviceManager'; +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} -store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { - if (err) { - console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); - return; - } - console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); +store.obtainDistributedTableName(deviceId, "EMPLOYEE", (err, tableName) => { + if (err) { + console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); + return; + } + console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }) ``` @@ -3738,7 +3947,7 @@ Obtains the distributed table name of a remote device based on the local table n > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3768,24 +3977,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceId = null; +import deviceManager from '@ohos.distributedDeviceManager'; +import { BusinessError } from "@ohos.base"; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; + +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let promise = store.obtainDistributedTableName(deviceId, "EMPLOYEE"); -promise.then((tableName) => { +promise.then((tableName: string) => { console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3819,25 +4028,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceIds = []; +import deviceManager from '@ohos.distributedDeviceManager'; +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + for (let i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; + } +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); -store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { +store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => { if (err) { console.error(`Sync failed, code is ${err.code},message is ${err.message}`); return; @@ -3883,31 +4090,31 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceIds = []; +import deviceManager from '@ohos.distributedDeviceManager'; +import { BusinessError } from "@ohos.base"; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } -}) +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; + +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + for (let i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; + } +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates); -promise.then((result) =>{ +promise.then((result: Object[][]) =>{ console.info(`Sync done.`); for (let i = 0; i < result.length; i++) { console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); } -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Sync failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3933,14 +4140,14 @@ Manually starts device-cloud synchronization for all distributed tables. This AP **Example** ```js -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) { - console.info(`Progess: ${progressDetails}`); -}, function (err) { - if (err) { - console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); - return; - } - console.info('Cloud sync succeeded'); +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetails) => { + console.info(`Progess: ${progressDetails}`); +}, (err) =>{ + if (err) { + console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); + return; + } + console.info('Cloud sync succeeded'); }); ``` @@ -3970,13 +4177,13 @@ Manually starts device-cloud synchronization for all distributed tables. This AP **Example** ```js -function progress(progressDetail) { - console.info(`progress: ${progressDetail}`); -} +import { BusinessError } from "@ohos.base"; -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => { +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetail: relationalStore.ProgressDetails) => { + console.info(`progress: ${progressDetail}`); +}).then(() => { console.info('Cloud sync succeeded'); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -4004,14 +4211,14 @@ Manually starts device-cloud synchronization of the specified table. This API us ```js const tables = ["table1", "table2"]; -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) { - console.info(`Progess: ${progressDetails}`); -}, function (err) { - if (err) { - console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); - return; - } - console.info('Cloud sync succeeded'); +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, (progressDetail: relationalStore.ProgressDetails) => { + console.info(`Progess: ${progressDetails}`); +}, (err) => { + if (err) { + console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); + return; + } + console.info('Cloud sync succeeded'); }); ``` @@ -4042,14 +4249,15 @@ Manually starts device-cloud synchronization of the specified table. This API us **Example** ```js +import { BusinessError } from "@ohos.base"; + const tables = ["table1", "table2"]; -function progress(progressDetail) { - console.info(`progress: ${progressDetail}`); -} -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => { +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetail: relationalStore.ProgressDetails) => { + console.info(`progress: ${progressDetail}`); +}).then(() => { console.info('Cloud sync succeeded'); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -4073,13 +4281,15 @@ Registers a data change event listener for the RDB store. When the data in the R **Example** ```js -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.info(`device= ${devices[i]} data changed`); - } -} +import deviceManager from '@ohos.distributedHardware.deviceManager'; try { - store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => { + let devices: string; + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } + } + ); } catch (err) { console.error(`Register observer failed, code is ${err.code},message is ${err.message}`); } @@ -4104,6 +4314,7 @@ Registers a data change event listener for the RDB store. When the data in the R **Example** ```js +import deviceManager from '@ohos.distributedHardware.deviceManager'; function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { console.info(`device= ${devices[i]} data changed`); @@ -4129,7 +4340,7 @@ Registers an intra-process or inter-process event listener for the RDB store. Th | Name | Type | Mandatory| Description | | ------------ | --------------- | ---- | ------------------------------------------------------------ | | event | string | Yes | Event name to observe. | -| interProcess | boolean | Yes | Type of the event to observe.
The value **true** means the inter-process event.
The value **false** means the intra-process event. | +| interProcess | boolean | Yes | Type of the event to observe.
The value **true** means the inter-process event.
The value **false** means the intra-process event.| | observer | Callback\ | Yes | Callback invoked to return the result. | **Error codes** @@ -4144,11 +4355,10 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -function storeObserver() { - console.info(`storeObserver`); -} try { - store.on('storeObserver', false, storeObserver); + store.on('storeObserver', false, (storeObserver) => { + console.info(`storeObserver`); + }); } catch (err) { console.error(`Register observer failed, code is ${err.code},message is ${err.message}`); } @@ -4173,13 +4383,15 @@ Unregisters the data change event listener. **Example** ``` -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.info(`device= ${devices[i]} data changed`); - } -} +import deviceManager from '@ohos.distributedHardware.deviceManager'; try { - store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => { + let devices: string; + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } + } + ); } catch (err) { console.error(`Unregister observer failed, code is ${err.code},message is ${err.message}`); } @@ -4204,13 +4416,15 @@ Unregisters the data change event listener. **Example** ```js -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.info(`device= ${devices[i]} data changed`); - } -} +import deviceManager from '@ohos.distributedHardware.deviceManager'; try { - store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => { + let devices: string; + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } + } + ); } catch (err) { console.error(`Unregister observer failed, code is ${err.code},message is ${err.message}`); } @@ -4244,11 +4458,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -function storeObserver() { - console.info(`storeObserver`); -} try { - store.off('storeObserver', false, storeObserver); + store.off('storeObserver', false, (storeObserver) => { + console.info(`storeObserver`); + } + ); } catch (err) { console.error(`Register observer failed, code is ${err.code},message is ${err.message}`); } @@ -4292,11 +4506,11 @@ Provides APIs to access the result set obtained by querying the RDB store. A res Obtain the **resultSet** object first. ```js -let resultSet = null; +let resultSet: relationalStore.ResultSet = null; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("AGE", 18); let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((result) => { +promise.then((result: relationalStore.ResultSet) => { resultSet = result; console.info(`resultSet columnNames: ${resultSet.columnNames}`); console.info(`resultSet columnCount: ${resultSet.columnCount}`); @@ -4350,7 +4564,6 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -resultSet.goToFirstRow(); const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); @@ -4424,14 +4637,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise= store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goTo(1); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToRow @@ -4465,14 +4671,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToRow(5); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToFirstRow @@ -4501,14 +4700,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToFirstRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToLastRow @@ -4536,14 +4728,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToLastRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToNextRow @@ -4571,14 +4756,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToNextRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToPreviousRow @@ -4606,14 +4784,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToPreviousRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### getBlob @@ -4866,13 +5037,7 @@ Closes this result set. **Example** ```js -let predicatesClose = new relationalStore.RdbPredicates("EMPLOYEE"); -let promiseClose = store.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSet) => { resultSet.close(); -}).catch((err) => { - console.error(`resultset close failed, code is ${err.code},message is ${err.message}`); -}); ``` **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-data-udmf.md b/en/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md similarity index 70% rename from en/application-dev/reference/apis/js-apis-data-udmf.md rename to en/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md index cd2a07bc6b8f5df270f8fab7022f76a9e5615d9e..e75ea7e1ccc4b2439a953512b59f8b07e1147927 100644 --- a/en/application-dev/reference/apis/js-apis-data-udmf.md +++ b/en/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md @@ -1,6 +1,6 @@ -# @ohos.data.UDMF (Unified Data Management Framework) +# @ohos.data.unifiedDataChannel (Unified Data Channel) -The **UDMF** module provides unified data management capabilities, including standard definition of data types, such as text and image. By calling the APIs provided by this module, applications can encapsulate a variety of data into unified data objects. +As a part of the Unified Data Management Framework (UDMF), the **unifiedDataChannel** module provides unified data channels and standard data access interfaces for many-to-many data sharing across applications. It also provides standard definitions for data types, such as text and image, to streamline data interaction between different applications and minimize the workload of data type adaptation. > **NOTE** > @@ -9,32 +9,9 @@ The **UDMF** module provides unified data management capabilities, including sta ## Modules to Import ```js -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; ``` -## UnifiedDataType - -Enumerates the types of the [data records](#unifiedrecord) in the [unifiedData](#unifieddata) object. - -**System capability**: SystemCapability.DistributedDataManager.UDMF.Core - -| Name | Value | Description | -|----------------------------|------------------------------|-----------| -| TEXT | 'Text' | Text. | -| PLAIN_TEXT | 'Text.PlainText' | Plaintext. | -| HYPERLINK | 'Text.Hyperlink' | Hyperlink. | -| HTML | 'Text.HTML' | HyperText Markup Language (HTML). | -| FILE | 'File' | File. | -| IMAGE | 'File.Media.Image' | Image. | -| VIDEO | 'File.Media.Video' | Video. | -| AUDIO | 'File.Media.Audio' | Audio. | -| FOLDER | 'File.Folder' | Folder. | -| SYSTEM_DEFINED_RECORD | 'SystemDefinedType' | System ability data.| -| SYSTEM_DEFINED_FORM | 'SystemDefinedType.Form' | Widget. | -| SYSTEM_DEFINED_APP_ITEM | 'SystemDefinedType.AppItem' | Icon. | -| SYSTEM_DEFINED_PIXEL_MAP | 'SystemDefinedType.PixelMap' | Pixel map. | -| APPLICATION_DEFINED_RECORD | 'ApplicationDefinedType' | Application-defined type. | - ## UnifiedData Provides APIs for encapsulating a set of data records. @@ -58,9 +35,9 @@ A constructor used to create a **UnifiedData** object with a data record. **Example** ```js -let text = new UDMF.PlainText(); +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent of text'; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); ``` ### addRecord @@ -80,11 +57,11 @@ Adds a data record to this **UnifiedRecord** object. **Example** ```js -let text1 = new UDMF.PlainText(); +let text1 = new unifiedDataChannel.PlainText(); text1.textContent = 'this is textContent of text1'; -let unifiedData = new UDMF.UnifiedData(text1); +let unifiedData = new unifiedDataChannel.UnifiedData(text1); -let text2 = new UDMF.PlainText(); +let text2 = new unifiedDataChannel.PlainText(); text2.textContent = 'this is textContent of text2'; unifiedData.addRecord(text2); ``` @@ -106,22 +83,24 @@ Obtains all data records from this **UnifiedData** object. The data obtained is **Example** ```js -let text = new UDMF.PlainText(); +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; + +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent of text'; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); -let link = new UDMF.Hyperlink(); +let link = new unifiedDataChannel.Hyperlink(); link.url = 'www.XXX.com'; unifiedData.addRecord(link); let records = unifiedData.getRecords(); for (let i = 0; i < records.length; i++) { let record = records[i]; - if (record.getType() == UDMF.UnifiedDataType.PLAIN_TEXT) { - let plainText = (record); + if (record.getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let plainText = record as unifiedDataChannel.PlainText; console.info(`textContent: ${plainText.textContent}`); - } else if (record.getType() == UDMF.UnifiedDataType.HYPERLINK) { - let hyperlink = (record); + } else if (record.getType() == uniformTypeDescriptor.UniformDataType.HYPERLINK) { + let hyperlink = record as unifiedDataChannel.Hyperlink; console.info(`linkUrl: ${hyperlink.url}`); } } @@ -135,7 +114,7 @@ Defines the summary of a **UnifiedData object**, including the data types and si | Name | Type | Readable| Writable| Description | | --------- | ------------------------- | ---- | ---- |-----------------------------------------------------------------------------------| -| summary | { [key: string]: number } | Yes | No | A directory type object, where **key** indicates the data type (see [UnifiedDataType](#unifieddatatype)), and the value indicates the total size (in bytes) of this type of records in the **UnifiedData** object.| +| summary | { [key: string]: number } | Yes | No | Dictionary type object, where the key indicates the data type (see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype)), and the value indicates the total size (in bytes) of this type of records in the **UnifiedData** object.| | totalSize | number | Yes | No | Total size of all the records in the **UnifiedData** object, in bytes. | ## UnifiedRecord @@ -156,19 +135,21 @@ Obtains the type of this **UnfiedRecord**. The data obtained by [getRecords](#ge | Type | Description | | ------ |------------------------------------------------------| -| string | Data type obtained. For details, see [UnifiedDataType](#unifieddatatype).| +| string | Data type obtained. For details, see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype).| **Example** ```js -let text = new UDMF.PlainText(); +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; + +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent of text'; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); let records = unifiedData.getRecords(); -if (records[0].getType() == UDMF.UnifiedDataType.PLAIN_TEXT) { - let plainText = (records[0]); - console.info(`textContent: ${plainText.textContent}`); +if (records[0].getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let plainText = records[0] as unifiedDataChannel.PlainText; + console.info(`textContent: ${plainText.textContent}`); } ``` @@ -185,12 +166,12 @@ Represents the text data. It is a child class of [UnifiedRecord](#unifiedrecord) **Example** ```js -let text = new UDMF.Text(); +let text = new unifiedDataChannel.Text(); text.details = { title: 'MyTitle', content: 'this is content', }; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); ``` ## PlainText @@ -207,7 +188,7 @@ Represents the plaintext data. It is a child class of [Text](#text) and is used **Example** ```js -let text = new UDMF.PlainText(); +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent'; text.abstract = 'this is abstract'; ``` @@ -226,7 +207,7 @@ Represents hyperlink data. It is a child class of [Text](#text) and is used to d **Example** ```js -let link = new UDMF.Hyperlink(); +let link = new unifiedDataChannel.Hyperlink(); link.url = 'www.XXX.com'; link.description = 'this is description'; ``` @@ -245,7 +226,7 @@ Represents the HTML data. It is a child class of [Text](#text) and is used to de **Example** ```js -let html = new UDMF.HTML(); +let html = new unifiedDataChannel.HTML(); html.htmlContent = '

Title

'; html.plainContent = 'this is plainContent'; ``` @@ -264,7 +245,7 @@ Represents the file data. It is a child class of [UnifiedRecord](#unifiedrecord) **Example** ```js -let file = new UDMF.File(); +let file = new unifiedDataChannel.File(); file.details = { name: 'test', type: 'txt', @@ -285,7 +266,7 @@ Represents the image data. It is a child class of [File](#file) and is used to d **Example** ```js -let image = new UDMF.Image(); +let image = new unifiedDataChannel.Image(); image.imageUri = 'schema://com.samples.test/files/test.jpg'; ``` @@ -302,7 +283,7 @@ Represents video data. It is a child class of [File](#file) and is used to descr **Example** ```js -let video = new UDMF.Video(); +let video = new unifiedDataChannel.Video(); video.videoUri = 'schema://com.samples.test/files/test.mp4'; ``` @@ -319,7 +300,7 @@ Represents video data. It is a child class of [File](#file) and is used to descr **Example** ```js -let audio = new UDMF.Audio(); +let audio = new unifiedDataChannel.Audio(); audio.audioUri = 'schema://com.samples.test/files/test.mp3'; ``` @@ -336,7 +317,7 @@ Represents the folder data. It is a child class of [File](#file) and is used to **Example** ```js -let folder = new UDMF.Folder(); +let folder = new unifiedDataChannel.Folder(); folder.folderUri = 'schema://com.samples.test/files/folder/'; ``` @@ -353,14 +334,14 @@ Represents specific data types defined by OpenHarmony. It is a child class of [U **Example** ```js -let sdr = new UDMF.SystemDefinedRecord(); +let sdr = new unifiedDataChannel.SystemDefinedRecord(); let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); sdr.details = { title: 'recordTitle', version: 1, content: u8Array, }; -let unifiedData = new UDMF.UnifiedData(sdr); +let unifiedData = new unifiedDataChannel.UnifiedData(sdr); ``` ## SystemDefinedForm @@ -380,7 +361,7 @@ Represents the widget data. It is a child class of [SystemDefinedRecord](#system **Example** ```js -let form = new UDMF.SystemDefinedForm(); +let form = new unifiedDataChannel.SystemDefinedForm(); form.formId = 123456; form.formName = 'MyFormName'; form.bundleName = 'MyBundleName'; @@ -392,7 +373,7 @@ form.details = { formKey2: 'formValue', formKey3: u8Array, }; -let unifiedData = new UDMF.UnifiedData(form); +let unifiedData = new unifiedDataChannel.UnifiedData(form); ``` ## SystemDefinedAppItem @@ -413,7 +394,7 @@ Represents the icon data. It is a child class of [SystemDefinedRecord](#systemde **Example** ```js -let appItem = new UDMF.SystemDefinedAppItem(); +let appItem = new unifiedDataChannel.SystemDefinedAppItem(); appItem.appId = 'MyAppId'; appItem.appName = 'MyAppName'; appItem.appIconId = 'MyAppIconId'; @@ -426,7 +407,7 @@ appItem.details = { appItemKey2: 'appItemValue', appItemKey3: u8Array, }; -let unifiedData = new UDMF.UnifiedData(appItem); +let unifiedData = new unifiedDataChannel.UnifiedData(appItem); ``` ## SystemDefinedPixelMap @@ -445,19 +426,23 @@ Represents the image data corresponding to the [PixelMap](js-apis-image.md#pixel import image from '@ohos.multimedia.image'; // Module where the PixelMap class is defined. const color = new ArrayBuffer(96); // Create a PixelMap object. -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +let opts: image.InitializationOptions = { + editable: true, pixelFormat: 3, size: { + height: 4, width: 6 + } +} image.createPixelMap(color, opts, (error, pixelmap) => { - if(error) { - console.error('Failed to create pixelmap.'); - } else { - console.info('Succeeded in creating pixelmap.'); - let arrayBuf = new ArrayBuffer(pixelmap.getPixelBytesNumber()); - pixelmap.readPixelsToBuffer(arrayBuf); - let u8Array = new Uint8Array(arrayBuf); - let sdpixel = new UDMF.SystemDefinedPixelMap(); - sdpixel.rawData = u8Array; - let unifiedData = new UDMF.UnifiedData(sdpixel); - } + if (error) { + console.error('Failed to create pixelmap.'); + } else { + console.info('Succeeded in creating pixelmap.'); + let arrayBuf = new ArrayBuffer(pixelmap.getPixelBytesNumber()); + pixelmap.readPixelsToBuffer(arrayBuf); + let u8Array = new Uint8Array(arrayBuf); + let sdpixel = new unifiedDataChannel.SystemDefinedPixelMap(); + sdpixel.rawData = u8Array; + let unifiedData = new unifiedDataChannel.UnifiedData(sdpixel); + } }) ``` @@ -475,11 +460,11 @@ Represents the custom data type for applications only. It is a child class of [U **Example** ```js -let record = new UDMF.ApplicationDefinedRecord(); +let record = new unifiedDataChannel.ApplicationDefinedRecord(); let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); record.applicationDefinedType = 'ApplicationDefinedType'; record.rawData = u8Array; -let unifiedData = new UDMF.UnifiedData(record); +let unifiedData = new unifiedDataChannel.UnifiedData(record); ``` ## Intention @@ -502,11 +487,11 @@ Defines the data operation performed by the UDMF. It includes two optional param | Name | Type | Readable| Writable| Mandatory| Description | |-----------|-------------------------|----|----|----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | intention | [Intention](#intention) | Yes | Yes | No | Type of the data channel related to the data operation. | -| key | string | Yes | Yes | No | Unique identifier of a data object in the UDMF, which can be obtained from the return value of [insertData](#udmfinsertdata).
The key consists of **udmf:/**, **intention**, **bundleName**, and **groupId** with a (/) in between, for example, **udmf://DataHub/com.ohos.test/0123456789**.
**udmf:/** is fixed, **DataHub** is an enum of **intention**, **com.ohos.test** is the bundle name, and **0123456789** is a group ID randomly generated.| +| key | string | Yes | Yes | No | Unique identifier of the data object in the UDMF, which can be obtained from the value returned by [insertData](#unifieddatachannelinsertdata).
The key consists of **udmf:/**, **intention**, **bundleName**, and **groupId** with a (/) in between, for example, **udmf://DataHub/com.ohos.test/0123456789**.
**udmf:/** is fixed, **DataHub** is an enum of **intention**, **com.ohos.test** is the bundle name, and **0123456789** is a group ID randomly generated.| -## UDMF.insertData +## unifiedDataChannel.insertData insertData(options: Options, data: UnifiedData, callback: AsyncCallback<string>): void @@ -525,30 +510,32 @@ Inserts data to the UDMF public data channel. This API uses an asynchronous call **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - intention: UDMF.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB } try { - UDMF.insertData(options, unifiedData, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in inserting data. key = ${data}`); - } else { - console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); - } - }); -} catch(e) { - console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.insertData(options, unifiedData, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in inserting data. key = ${data}`); + } else { + console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); + } + }); + } catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `); } ``` -## UDMF.insertData +## unifiedDataChannel.insertData insertData(options: Options, data: UnifiedData): Promise<string> @@ -572,27 +559,29 @@ Inserts data to the UDMF public data channel. This API uses a promise to return **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - intention: UDMF.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB } try { - UDMF.insertData(options, unifiedData).then((data) => { - console.info(`Succeeded in inserting data. key = ${data}`); - }).catch((err) => { - console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.insertData(options, unifiedData).then((data) => { + console.info(`Succeeded in inserting data. key = ${data}`); + }).catch((err: BusinessError) => { + console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `); } ``` -## UDMF.updateData +## unifiedDataChannel.updateData updateData(options: Options, data: UnifiedData, callback: AsyncCallback<void>): void @@ -611,30 +600,32 @@ Updates the data in the UDMF public data channel. This API uses an asynchronous **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.updateData(options, unifiedData, (err) => { - if (err === undefined) { - console.info('Succeeded in updating data.'); - } else { - console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); - } - }); -} catch(e) { - console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.updateData(options, unifiedData, (err) => { + if (err === undefined) { + console.info('Succeeded in updating data.'); + } else { + console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); + } + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `); } ``` -## UDMF.updateData +## unifiedDataChannel.updateData updateData(options: Options, data: UnifiedData): Promise<void> @@ -658,28 +649,30 @@ Updates the data in the UDMF public data channel. This API uses a promise to ret **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.updateData(options, unifiedData).then(() => { - console.info('Succeeded in updating data.'); - }).catch((err) => { - console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.updateData(options, unifiedData).then(() => { + console.info('Succeeded in updating data.'); + }).catch((err: BusinessError) => { + console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `); } ``` -## UDMF.queryData +## unifiedDataChannel.queryData queryData(options: Options, callback: AsyncCallback<Array<UnifiedData>>): void @@ -697,35 +690,38 @@ Queries data in the UDMF public data channel. This API uses an asynchronous call **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - intention: UDMF.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - UDMF.queryData(options, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in querying data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } - } - } else { - console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + unifiedDataChannel.queryData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in querying data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); + } } - }); -} catch(e) { - console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); + } + } else { + console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + } + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `); } ``` -## UDMF.queryData +## unifiedDataChannel.queryData queryData(options: Options): Promise<Array<UnifiedData>> @@ -748,33 +744,36 @@ Queries data in the UDMF public data channel. This API uses a promise to return **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.queryData(options).then((data) => { - console.info(`Succeeded in querying data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } + unifiedDataChannel.queryData(options).then((data) => { + console.info(`Succeeded in querying data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); } - }).catch((err) => { - console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); + } + } + }).catch((err: BusinessError) => { + console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `); } ``` -## UDMF.deleteData +## unifiedDataChannel.deleteData deleteData(options: Options, callback: AsyncCallback<Array<UnifiedData>>): void @@ -792,35 +791,38 @@ Deletes data from the UDMF public data channel. This API uses an asynchronous ca **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - intention: UDMF.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - UDMF.deleteData(options, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in deleting data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } - } - } else { - console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + unifiedDataChannel.deleteData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in deleting data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); + } } - }); -} catch(e) { - console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); + } + } else { + console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + } + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `); } ``` -## UDMF.deleteData +## unifiedDataChannel.deleteData deleteData(options: Options): Promise<Array<UnifiedData>> @@ -843,28 +845,31 @@ Deletes data from the UDMF public data channel. This API uses a promise to retur **Example** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.deleteData(options).then((data) => { - console.info(`Succeeded in deleting data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } + unifiedDataChannel.deleteData(options).then((data) => { + console.info(`Succeeded in deleting data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); } - }).catch((err) => { - console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); + } + } + }).catch((err: BusinessError) => { + console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `); } ``` diff --git a/en/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md b/en/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md new file mode 100644 index 0000000000000000000000000000000000000000..edf2e5ac34b0785ffe2c5076badfabc80221d2b5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md @@ -0,0 +1,34 @@ +# @ohos.data.uniformTypeDescriptor (Standard Data Definition) + +The **uniformTypeDescriptor** module provides abstract definitions of OpenHarmony standardized data types. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +``` + +## UniformDataType + +Enumerates the types of OpenHarmony standard data. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Value | Description | +|----------------------------|------------------------------|-----------| +| TEXT | 'general.text' | Text. | +| PLAIN_TEXT | 'general.plain-text' | Plaintext. | +| HYPERLINK | 'general.hyperlink' | Hyperlink. | +| HTML | 'general.html' | HyperText Markup Language (HTML). | +| FILE | 'general.file' | File. | +| IMAGE | 'general.image' | Image. | +| VIDEO | 'general.video' | Video. | +| AUDIO | 'general.audio' | Audio. | +| FOLDER | 'general.folder' | Folder. | +| OPENHARMONY_FORM | 'openharmony.form' | Widget. | +| OPENHARMONY_APP_ITEM | 'openharmony.app-item' | Icon. | +| OPENHARMONY_PIXEL_MAP | 'openharmony.pixel-map' | Pixel map. | diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md index 6cde0cf71b73660bf168b36feac2805753f08b79..2a4e91e3d798268e945744cf2c3d90755357dd32 100644 --- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -12,8 +12,7 @@ The **distributedKVStore** module provides the following functions: > **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. -> - All the APIs that need to obtain **deviceId** in this module are available only to system applications. +> 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 @@ -2030,7 +2029,7 @@ deviceId(deviceId:string):Query Creates a **Query** object with the device ID as the key prefix. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2819,7 +2818,7 @@ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void Deletes data of a device. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -2871,7 +2870,7 @@ removeDeviceData(deviceId: string): Promise<void> Deletes data of a device. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4550,7 +4549,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > -> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4576,40 +4575,41 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let devManager; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; // create deviceManager -deviceManager.createDeviceManager('bundleName', (err, value) => { - if (!err) { - devManager = value; - let deviceIds = []; - if (devManager != null) { - var devices = devManager.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].networkId; - } - } - try { - kvStore.on('syncComplete', function (data) { - console.info('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { - if (err != undefined) { - console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); - return; - } - console.info('Succeeded in putting data'); - const mode = distributedKVStore.SyncMode.PULL_ONLY; - kvStore.sync(deviceIds, mode, 1000); - }); - } catch (e) { - console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); +try { + devManager = deviceManager.createDeviceManager(context.applicationInfo.name); + let deviceIds = []; + if (devManager != null) { + var devices = devManager.getAvailableDeviceListSync(); + for (var i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; } } -}); + try { + kvStore.on('syncComplete', function (data) { + console.info('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { + if (err != undefined) { + console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in putting data'); + const mode = distributedKVStore.SyncMode.PULL_ONLY; + kvStore.sync(deviceIds, mode, 1000); + }); + } catch (e) { + console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); + } + +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} ``` ### sync @@ -4619,7 +4619,7 @@ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > -> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4646,43 +4646,44 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let devManager; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; // create deviceManager -deviceManager.createDeviceManager('bundleName', (err, value) => { - if (!err) { - devManager = value; - let deviceIds = []; - if (devManager != null) { - var devices = devManager.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].networkId; - } - } - try { - kvStore.on('syncComplete', function (data) { - console.info('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { - if (err != undefined) { - console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); - return; - } - console.info('Succeeded in putting data'); - const mode = distributedKVStore.SyncMode.PULL_ONLY; - const query = new distributedKVStore.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(deviceIds, query, mode, 1000); - }); - } catch (e) { - console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); +try { + let devManager = deviceManager.createDeviceManager(context.applicationInfo.name); + let deviceIds = []; + if (devManager != null) { + var devices = devManager.getAvailableDeviceListSync(); + for (var i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; } } -}); + try { + kvStore.on('syncComplete', function (data) { + console.info('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { + if (err != undefined) { + console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in putting data'); + const mode = distributedKVStore.SyncMode.PULL_ONLY; + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + query.deviceId(devManager.getLocalDeviceNetworkId()); + kvStore.sync(deviceIds, query, mode, 1000); + }); + } catch (e) { + console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); + } + +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} ``` ### on('dataChange') @@ -5046,7 +5047,7 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5101,7 +5102,7 @@ get(deviceId: string, key: string): Promise<boolean | string | number | Uint8 Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5281,7 +5282,7 @@ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5348,7 +5349,7 @@ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5544,7 +5545,7 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]> Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5616,7 +5617,7 @@ getEntries(deviceId: string, query: Query): Promise<Entry[]> Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5824,7 +5825,7 @@ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVS Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5879,7 +5880,7 @@ getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet&g Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5935,7 +5936,7 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreR Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6011,7 +6012,7 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6154,7 +6155,7 @@ getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -6343,7 +6344,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System API**: This is a system API. @@ -6404,7 +6405,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System API**: This is a system API. @@ -6585,7 +6586,7 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number& Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6651,7 +6652,7 @@ getResultSize(deviceId: string, query: Query): Promise<number> Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore diff --git a/zh-cn/application-dev/IDL/idl-guidelines.md b/zh-cn/application-dev/IDL/idl-guidelines.md index 655734d746a9ac6894c629e848d80832fb5362f4..a128c83266d6e629fdcb261288315a1d4e63bddd 100644 --- a/zh-cn/application-dev/IDL/idl-guidelines.md +++ b/zh-cn/application-dev/IDL/idl-guidelines.md @@ -156,7 +156,9 @@ OpenHarmony IDL容器数据类型与Ts数据类型、C++数据类型的对应关 进入对应路径后,查看toolchains->3.x.x.x(对应版本号命名文件夹)下是否存在idl工具的可执行文件。 -> **注意**:请保证使用最新版的SDK,版本老旧可能导致部分语句报错。 +> **注意**: +> +> 请保证使用最新版的SDK,版本老旧可能导致部分语句报错。 若不存在,可对应版本前往[docs仓版本目录](../../release-notes)下载SDK包,以[3.2Beta3版本](../../release-notes/OpenHarmony-v3.2-beta3.md)为例,可通过镜像站点获取。 @@ -185,7 +187,9 @@ OpenHarmony IDL容器数据类型与Ts数据类型、C++数据类型的对应关 -d后的dir为目标输出目录,以输出文件夹名为IIdlTestServiceTs为例,在idl可执行文件所在目录下执行`idl -gen-ts -d IIdlTestServiceTs -c IIdlTestServiceTs/IIdlTestService.idl`,将会在执行环境的dir目录(即IIdlTestServiceTs目录)中生成接口文件、Stub文件、Proxy文件。 -> **注意**:生成的接口类文件名称和.idl文件名称保持一致,否则会生成代码时会出现错误。 +> **注意**: +> +> 生成的接口类文件名称和.idl文件名称保持一致,否则会生成代码时会出现错误。 以名为`IIdlTestService.idl`的.idl文件、目标输出文件夹为IIdlTestServiceTs为例,其目录结构应类似于: diff --git a/zh-cn/application-dev/application-models/uiability-launch-type.md b/zh-cn/application-dev/application-models/uiability-launch-type.md index 02e7b462de19e391884cde28f326c6a5cb8e7dd2..4f4e8841e19d72c5585c15e234d11c0a5916f164 100644 --- a/zh-cn/application-dev/application-models/uiability-launch-type.md +++ b/zh-cn/application-dev/application-models/uiability-launch-type.md @@ -20,7 +20,9 @@ singleton启动模式为单实例模式,也是默认情况下的启动模式 **图1** 单实例模式演示效果 ![uiability-launch-type1](figures/uiability-launch-type1.gif) -> **说明**:应用的UIAbility实例已创建,该UIAbility配置为单实例模式,再次调用[`startAbility()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动该UIAbility实例。由于启动的还是原来的UIAbility实例,并未重新创建一个新的UIAbility实例,此时只会进入该UIAbility的[`onNewWant()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)和[`onWindowStageCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate)生命周期回调。 +> **说明**: +> +> 应用的UIAbility实例已创建,该UIAbility配置为单实例模式,再次调用[`startAbility()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动该UIAbility实例。由于启动的还是原来的UIAbility实例,并未重新创建一个新的UIAbility实例,此时只会进入该UIAbility的[`onNewWant()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant)回调,不会进入其[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)和[`onWindowStageCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate)生命周期回调。 如果需要使用singleton启动模式,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的`launchType`字段配置为`singleton`即可。 diff --git a/zh-cn/application-dev/application-models/uiability-lifecycle.md b/zh-cn/application-dev/application-models/uiability-lifecycle.md index 1df4b383b8423e2ff57f9eb0a7c8ae29f7cc167f..719f677b634b400de2428b70cec80d3285dd12a7 100644 --- a/zh-cn/application-dev/application-models/uiability-lifecycle.md +++ b/zh-cn/application-dev/application-models/uiability-lifecycle.md @@ -32,7 +32,9 @@ export default class EntryAbility extends UIAbility { } ``` -> **说明**:[Want](../reference/apis/js-apis-app-ability-want.md)是对象间信息传递的载体,可以用于应用组件间的信息传递。Want的详细介绍请参见[信息传递载体Want](want-overview.md)。 +> **说明**: +> +> [Want](../reference/apis/js-apis-app-ability-want.md)是对象间信息传递的载体,可以用于应用组件间的信息传递。Want的详细介绍请参见[信息传递载体Want](want-overview.md)。 ### WindowStageCreate和WindowStageDestory状态 diff --git a/zh-cn/application-dev/connectivity/ipc-rpc-development-guideline.md b/zh-cn/application-dev/connectivity/ipc-rpc-development-guideline.md index 62c009f09cb741ef35b98248ba06a622bb35e5f2..e1ff64c0938c61877cc36f0aa3f314c1e80ebf5a 100755 --- a/zh-cn/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/zh-cn/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -166,10 +166,10 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); sptr remoteObject = samgr->GetSystemAbility(saId); sptr testAbility = iface_cast(remoteObject); // 使用iface_cast宏转换成具体类型 - + // 获取其他设备注册的SA的proxy sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - + // networkId是组网场景下对应设备的标识符,可以通过GetLocalNodeDeviceInfo获取 sptr remoteObject = samgr->GetSystemAbility(saId, networkId); sptr proxy(new TestAbilityProxy(remoteObject)); // 直接构造具体Proxy @@ -231,8 +231,10 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; import deviceManager from '@ohos.distributedHardware.deviceManager'; + import { BusinessError } from '@ohos.base'; - let proxy: rpc.RemoteProxy; + let dmInstance: deviceManager.DeviceManager | undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connectId: number; // 单个设备绑定Ability @@ -242,7 +244,7 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, abilityName: "ohos.rpc.test.server.ServiceAbility", }; let connect: common.ConnectOptions = { - onConnect: (elementName, remote: rpc.RemoteProxy) => { + onConnect: (elementName, remote) => { proxy = remote; }, onDisconnect: (elementName) => { @@ -259,29 +261,36 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, // 跨设备绑定 let deviceManagerCallback = (err: BusinessError, data: deviceManager.DeviceManager) => { if (err) { - console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); - return; + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + return; } console.info("createDeviceManager success"); - let dmInstance = data; + dmInstance = data; + } + try{ + deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback); + } catch(error) { + let e: BusinessError = error as BusinessError; + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } + + // 使用deviceManager获取目标设备NetworkId + if (dmInstance != undefined) { + let deviceList: Array = dmInstance.getTrustedDeviceListSync(); + let networkId: string = deviceList[0].networkId; + let want: Want = { + bundleName: "ohos.rpc.test.server", + abilityName: "ohos.rpc.test.service.ServiceAbility", + deviceId: networkId, + flags: 256 + }; + // 建立连接后返回的Id需要保存下来,在断开连接时需要作为参数传入 + // FA模型使用此方法连接服务 + // connectId = featureAbility.connectAbility(want, connect); + + // 第一个参数是本应用的包名,第二个参数是接收deviceManager的回调函数 + connectId = this.context.connectServiceExtensionAbility(want,connect); } - deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback); - - // 使用deviceManager获取目标设备NetworkId - let deviceList: Array = dmInstance.getTrustedDeviceListSync(); - let networkId: string = deviceList[0].networkId; - let want: Want = { - bundleName: "ohos.rpc.test.server", - abilityName: "ohos.rpc.test.service.ServiceAbility", - deviceId: networkId, - flags: 256 - }; - // 建立连接后返回的Id需要保存下来,在断开连接时需要作为参数传入 - // FA模型使用此方法连接服务 - // connectId = featureAbility.connectAbility(want, connect); - - // 第一个参数是本应用的包名,第二个参数是接收deviceManager的回调函数 - connectId = this.context.connectServiceExtensionAbility(want,connect); ``` 3. 服务端处理客户端请求 @@ -289,11 +298,7 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, 服务端被绑定的Ability在onConnect方法里返回继承自rpc.RemoteObject的对象,该对象需要实现onRemoteMessageRequest方法,处理客户端的请求。 ```ts - onConnect(want: Want) { - const robj: rpc.RemoteObject = new Stub("rpcTestAbility"); - return robj; - } - class Stub extends rpc.RemoteObject { + class Stub extends rpc.RemoteObject { constructor(descriptor: string) { super(descriptor); } @@ -301,7 +306,11 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, // 根据code处理客户端的请求 return true; } - } + } + onConnect(want: Want) { + const robj: rpc.RemoteObject = new Stub("rpcTestAbility"); + return robj; + } ``` 4. 客户端处理服务端响应 @@ -359,6 +368,7 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, import rpc from "@ohos.rpc"; // 仅FA模型需要导入@ohos.ability.featureAbility // import featureAbility from "@ohos.ability.featureAbility"; + function disconnectCallback() { console.info("disconnect ability done"); } diff --git a/zh-cn/application-dev/connectivity/subscribe-remote-state.md b/zh-cn/application-dev/connectivity/subscribe-remote-state.md index 15c6fc81feba681b646214925331346561d104ff..daed813db0a17625450c39a4c748a8208e53d9e0 100755 --- a/zh-cn/application-dev/connectivity/subscribe-remote-state.md +++ b/zh-cn/application-dev/connectivity/subscribe-remote-state.md @@ -98,7 +98,6 @@ import Want from '@ohos.app.ability.Want'; import AbilityConstant from '@ohos.app.ability.AbilityConstant'; import window from '@ohos.window'; - export default class MainAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("[Demo] MainAbility onCreate"); @@ -134,9 +133,9 @@ export default class MainAbility extends UIAbility { import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; -let proxy: rpc.RemoteProxy; +let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { - onConnect: (elementName, remoteProxy: rpc.RemoteProxy) => { + onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, diff --git a/zh-cn/application-dev/dfx/hitracechain-guidelines.md b/zh-cn/application-dev/dfx/hitracechain-guidelines.md index 71c98626619fb52c6e90b1ed3680077c59ffacbc..885f279aa41c61cc93c14c92f443ab14a3e4f84b 100644 --- a/zh-cn/application-dev/dfx/hitracechain-guidelines.md +++ b/zh-cn/application-dev/dfx/hitracechain-guidelines.md @@ -30,6 +30,7 @@ hiTraceChain是基于云计算分布式跟踪调用链思想,在端侧业务 ```ts import hiTraceChain from '@ohos.hiTraceChain'; import hiSysEvent from '@ohos.hiSysEvent'; + import { BusinessError } from '@ohos.base'; @Entry @Component @@ -50,26 +51,28 @@ hiTraceChain是基于云计算分布式跟踪调用链思想,在端侧业务 // 业务开始前,开启分布式跟踪。 let traceId = hiTraceChain.begin("Write a new system event", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC); // 业务开始:完成一次系统事件打点。 - hiSysEvent.write({ + let customizedParams: Record = { + 'PID': 1, + 'UID': 1, + 'PACKAGE_NAME': "com.demo.hitracechain", + 'PROCESS_NAME': "hitracechaindemo", + 'MSG': "no msg." + } + let eventInfo: hiSysEvent.SysEventInfo = { domain: "RELIABILITY", name: "STACK", eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 1, - UID: 1, - PACKAGE_NAME: "com.demo.hitracechain", - PROCESS_NAME: "hitracechaindemo", - MSG: "no msg." - } - }).then((val) => { + params: customizedParams + } + hiSysEvent.write(eventInfo).then((val: number) => { console.info(`write result is ${val}`); // 业务结束,关闭分布式跟踪。 hiTraceChain.end(traceId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`error message is ${err.message}`); }); } catch (err) { - console.error(`error message is ${err.message}`); + console.error(`error message is ${(err as BusinessError).message}`); } }) } diff --git a/zh-cn/application-dev/media/camera-mode.md b/zh-cn/application-dev/media/camera-mode.md index 8e52eae306727aff9c984093009b10833e26fcac..099430060bd8162d4626158943180a713efdaa98 100644 --- a/zh-cn/application-dev/media/camera-mode.md +++ b/zh-cn/application-dev/media/camera-mode.md @@ -1,4 +1,4 @@ -# 人像模式拍照实现方案 +# 使用人像模式拍照 ## 开发流程 diff --git a/zh-cn/application-dev/media/image-encoding.md b/zh-cn/application-dev/media/image-encoding.md index 8a5ab62e15e1842b56b39994b115d15d143a92be..a46249957ffc4c56c1b53358142b58ae1d41b9cc 100644 --- a/zh-cn/application-dev/media/image-encoding.md +++ b/zh-cn/application-dev/media/image-encoding.md @@ -30,9 +30,10 @@ 方法一:通过PixelMap进行编码。 ```ts - imagePackerApi.packing(pixelMap, packOpts).then( data => { + import {BusinessError} from '@ohos.base' + imagePackerApi.packing(pixelMap, packOpts).then( (data : ArrayBuffer) => { // data 为打包获取到的文件流,写入文件保存即可得到一张图片 - }).catch(error => { + }).catch((error : BusinessError) => { console.error('Failed to pack the image. And the error is: ' + error); }) ``` @@ -40,9 +41,10 @@ 方法二:通过imageSource进行编码。 ```ts - imagePackerApi.packing(imageSource, packOpts).then( data => { + import {BusinessError} from '@ohos.base' + imagePackerApi.packing(imageSource, packOpts).then( (data : ArrayBuffer) => { // data 为打包获取到的文件流,写入文件保存即可得到一张图片 - }).catch(error => { + }).catch((error : BusinessError) => { console.error('Failed to pack the image. And the error is: ' + error); }) ``` diff --git a/zh-cn/application-dev/media/image-pixelmap-operation.md b/zh-cn/application-dev/media/image-pixelmap-operation.md index a28daf42e51a3f40ed47d11ef69c8e14ba9c13c0..b1d7e746ecff96cd8e478fe30d26bc3537381bfa 100644 --- a/zh-cn/application-dev/media/image-pixelmap-operation.md +++ b/zh-cn/application-dev/media/image-pixelmap-operation.md @@ -27,11 +27,12 @@ 3. 读取并修改目标区域像素数据,写回原图。 ```ts + import {BusinessError} from '@ohos.base' // 场景一:将读取的整张图像像素数据结果写入ArrayBuffer中 const readBuffer = new ArrayBuffer(pixelBytesNumber); pixelMap.readPixelsToBuffer(readBuffer).then(() => { console.info('Succeeded in reading image pixel data.'); - }).catch(error => { + }).catch((error : BusinessError) => { console.error('Failed to read image pixel data. And the error is: ' + error); }) @@ -44,7 +45,7 @@ } pixelMap.readPixels(area).then(() => { console.info('Succeeded in reading the image data in the area.'); - }).catch(error => { + }).catch((error : BusinessError) => { console.error('Failed to read the image data in the area. And the error is: ' + error); }) diff --git a/zh-cn/application-dev/quick-start/arkts-mvvm.md b/zh-cn/application-dev/quick-start/arkts-mvvm.md index 1df7f939eb12e01c165ff1a207883ca1b4533385..ca4ef0d0aeba15e50322092cbdf580957a289191 100644 --- a/zh-cn/application-dev/quick-start/arkts-mvvm.md +++ b/zh-cn/application-dev/quick-start/arkts-mvvm.md @@ -621,7 +621,7 @@ struct Parent { ```ts class Outer { - innerArrayProp : ObservedArray; + innerArrayProp : ObservedArray = []; ... } ``` @@ -689,7 +689,7 @@ struct ViewB { (item: ClassA) => { ViewA({ label: `#${item.id}`, a: item }) }, - (item: ClassA) => item.id.toString() + (item: ClassA): string => { return item.id.toString(); } ) Divider().height(10) @@ -738,7 +738,7 @@ struct ViewB { @Component struct ViewA { - @Prop a: ClassA; + @Prop a: ClassA = new ClassA(0); label : string = "ViewA1"; build() { @@ -903,7 +903,7 @@ export class ObservedArray extends Array { @ObjectLink me : Person; @ObjectLink contacts : ObservedArray; - @State selectedPerson: Person = undefined; + @State selectedPerson: Person = new Person("", "", 0, "", []); aboutToAppear() { this.selectedPerson = this.me; @@ -919,7 +919,7 @@ export class ObservedArray extends Array { ForEach(this.contacts, (contact: Person) => { PersonView({ person: contact, phones: contact.phones as ObservedArray, selectedPerson: this.$selectedPerson }) }, - (contact: Person) => contact.id_ + (contact: Person): string => { return contact.id_; } ) Divider().height(8) @@ -1295,7 +1295,7 @@ export class ObservedArray extends Array { ForEach(this.contacts, (contact: Person) => { PersonView({ person: contact, phones: contact.phones as ObservedArray, selectedPerson: this.$selectedPerson }) }, - (contact: Person) => contact.id_ + (contact: Person): string => { return contact.id_; } ) Divider().height(8) diff --git a/zh-cn/application-dev/quick-start/arkts-state-management-best-practices.md b/zh-cn/application-dev/quick-start/arkts-state-management-best-practices.md index d52f598d46194893d98f6d2cf03e3613584f3352..0e45a6cd2747c6dddcd21fd7e9d98f0218abb152 100644 --- a/zh-cn/application-dev/quick-start/arkts-state-management-best-practices.md +++ b/zh-cn/application-dev/quick-start/arkts-state-management-best-practices.md @@ -507,8 +507,8 @@ incrSubCounter和setSubCounter都是同一个SubCounter的函数。在第一个 ```ts -@ObjectLink value:ParentCounter; -@ObjectLink subValue:SubCounter; +@ObjectLink value:ParentCounter = new ParentCounter(0); +@ObjectLink subValue:SubCounter = new SubCounter(0); ``` 该方法使得\@ObjectLink分别代理了ParentCounter和SubCounter的属性,这样对于这两个类的属性的变化都可以观察到,即都会对UI视图进行刷新。即使删除了上面所说的this.counter[0].incrCounter(),UI也会进行正确的刷新。 @@ -715,8 +715,8 @@ struct ParentComp { ```ts @Component struct CounterComp { - @Prop value: ParentCounter; - @Prop subValue: SubCounter; + @Prop value: ParentCounter = new ParentCounter(0); + @Prop subValue: SubCounter = new SubCounter(0); build() { Column({ space: 10 }) { Text(`this.subValue.counter: ${this.subValue.counter}`) @@ -948,8 +948,8 @@ build函数中更改应用状态的行为可能会比上面的示例更加隐蔽 ```ts -@State arr : Array<..> = [ ... ]; -ForEach(this.arr.sort().filter(....), +@State arr : Array<...> = [ ... ]; +ForEach(this.arr.sort().filter(...), item => { ... }) @@ -959,7 +959,7 @@ ForEach(this.arr.sort().filter(....), ```ts -ForEach(this.arr.filter(....).sort(), +ForEach(this.arr.filter(...).sort(), item => { ... }) diff --git a/zh-cn/application-dev/quick-start/arkts-watch.md b/zh-cn/application-dev/quick-start/arkts-watch.md index e607f0ff85eecf73de45c2d0a39696e32d30de8c..d683b300837f715ded2ec2c28c5e25155746dcca 100644 --- a/zh-cn/application-dev/quick-start/arkts-watch.md +++ b/zh-cn/application-dev/quick-start/arkts-watch.md @@ -60,7 +60,7 @@ ```ts @Component struct TotalView { - @Prop @Watch('onCountUpdated') count: number; + @Prop @Watch('onCountUpdated') count: number = 0; @State total: number = 0; // @Watch cb onCountUpdated(propName: string): void { diff --git a/zh-cn/application-dev/quick-start/in-app-hsp.md b/zh-cn/application-dev/quick-start/in-app-hsp.md index ec946f0d0ed437391649202d4065234283e4f1cd..d6b6a264c3ba64ed167630eafa71621f7560b514 100644 --- a/zh-cn/application-dev/quick-start/in-app-hsp.md +++ b/zh-cn/application-dev/quick-start/in-app-hsp.md @@ -145,6 +145,7 @@ export { nativeMulti } from './utils/nativeTest' ```ts // entry/src/main/ets/pages/index.ets import { Log, add, MyTitleBar, ResManager, nativeMulti } from "library" +import { BusinessError } from '@ohos.base'; @Entry @Component @@ -172,7 +173,7 @@ struct Index { .then(value => { console.log("getStringValue is " + value); }) - .catch(error => { + .catch((err: BusinessError) => { console.log("getStringValue promise error is " + error); }); }) diff --git a/zh-cn/application-dev/quick-start/start-with-ets-stage.md b/zh-cn/application-dev/quick-start/start-with-ets-stage.md index 04f63893d96bfd9ced996ed1f9d3f5c40b30142a..df621f42039411cf1ddb3159df48baf100cf5f4e 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-stage.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-stage.md @@ -275,6 +275,7 @@ // Index.ets // 导入页面路由模块 import router from '@ohos.router'; + import { BusinessError } from '@ohos.base'; @Entry @Component @@ -306,7 +307,7 @@ // 跳转到第二页 router.pushUrl({ url: 'pages/Second' }).then(() => { console.info('Succeeded in jumping to the second page.') - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`) }) }) @@ -326,6 +327,7 @@ // Second.ets // 导入页面路由模块 import router from '@ohos.router'; + import { BusinessError } from '@ohos.base'; @Entry @Component @@ -358,7 +360,9 @@ router.back() console.info('Succeeded in returning to the first page.') } catch (err) { - console.error(`Failed to return to the first page.Code is ${err.code}, message is ${err.message}`) + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to return to the first page.Code is ${code}, message is ${message}`) } }) } diff --git a/zh-cn/application-dev/reference/apis/js-apis-animator.md b/zh-cn/application-dev/reference/apis/js-apis-animator.md index 85c18a6f4287806f75037baa455d91fc3e600e20..1898cc188ec08a0edb9530639d187a81759dca1c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-animator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-animator.md @@ -14,8 +14,9 @@ ## 导入模块 -```js -import animator from '@ohos.animator'; +```ts +import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator'; +import { BusinessError } from '@ohos.base'; ``` ## create9+ @@ -39,10 +40,9 @@ create(options: AnimatorOptions): AnimatorResult **示例:** - ```js -import animator, { AnimatorOptions } from '@ohos.animator'; - -let options: AnimatorOptions = { // xxx.js文件中不需要强调显式类型AnimatorOptions + ```ts +import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator'; +let options: AnimatorOptions = { duration: 1500, easing: "friction", delay: 0, @@ -84,8 +84,10 @@ reset(options: AnimatorOptions): void **示例:** -```js -let options: AnimatorOptions = { // xxx.js文件中不需要强调显式类型AnimatorOptions +```ts +import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator'; +import { BusinessError } from '@ohos.base'; +let options: AnimatorOptions = { duration: 1500, easing: "friction", delay: 0, @@ -98,7 +100,9 @@ let options: AnimatorOptions = { // xxx.js文件中不需要强调显式类型An try { animator.reset(options); } catch(error) { - console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`); + let message = (error as BusinessError).message + let code = (error as BusinessError).code + console.error(`Animator reset failed, error code: ${code}, message: ${message}.`); } ``` @@ -112,7 +116,7 @@ play(): void **示例:** -```js +```ts animator.play(); ``` @@ -126,7 +130,7 @@ finish(): void **示例:** -```js +```ts animator.finish(); ``` @@ -140,7 +144,7 @@ pause(): void **示例:** -```js +```ts animator.pause(); ``` @@ -154,7 +158,7 @@ cancel(): void **示例:** -```js +```ts animator.cancel(); ``` @@ -168,7 +172,7 @@ reverse(): void **示例:** -```js +```ts animator.reverse(); ``` @@ -188,9 +192,10 @@ onframe: (progress: number) => void **示例:** -```js -let animatorResult = animator.create(options) -animatorResult.onframe = function(value) { +```ts +import animator, { AnimatorResult } from '@ohos.animator'; +let animatorResult:AnimatorResult|undefined = animator.create(options) +animatorResult.onframe = (value)=> { console.info("onframe callback") } ``` @@ -205,9 +210,10 @@ onfinish: () => void **示例:** -```js -let animatorResult = animator.create(options) -animatorResult.onfinish = function() { +```ts +import animator, { AnimatorResult } from '@ohos.animator'; +let animatorResult:AnimatorResult|undefined = animator.create(options) +animatorResult.onfinish = ()=> { console.info("onfinish callback") } ``` @@ -222,9 +228,10 @@ oncancel: () => void **示例:** -```js -let animatorResult = animator.create(options) -animatorResult.oncancel = function() { +```ts +import animator, { AnimatorResult } from '@ohos.animator'; +let animatorResult:AnimatorResult|undefined = animator.create(options) +animatorResult.oncancel = ()=> { console.info("oncancel callback") } ``` @@ -239,9 +246,10 @@ onrepeat: () => void **示例:** -```js -let animatorResult = animator.create(options) -animatorResult.onrepeat = function() { +```ts +import animator, { AnimatorResult } from '@ohos.animator'; +let animatorResult:AnimatorResult|undefined = animator.create(options) +animatorResult.onrepeat = ()=> { console.info("onrepeat callback") } ``` @@ -277,15 +285,28 @@ animatorResult.onrepeat = function() { ``` -```js -export default { - data: { - divWidth: 200, - divHeight: 200, - animator: null - }, +```ts +import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator'; +import { BusinessError } from '@ohos.base'; +let DataTmp:Record = { + 'divWidth': 200, + 'divHeight': 200, + 'animator': animator +} +class Tmp{ + data:animator = DataTmp + onInit:Function = ()=>{} + Show:Function = ()=>{} +} +class DateT{ + divWidth:number = 0 + divHeight:number = 0 + animator:AnimatorResult | null = null +} +(Fn:(v:Tmp) => void) => {Fn({ + data: DataTmp, onInit() { - let options = { + let options:AnimatorOptions = { duration: 1500, easing: "friction", delay: 0, @@ -295,10 +316,15 @@ export default { begin: 200.0, end: 400.0 }; - this.animator = animator.create(options); + let DataTmp:DateT = { + divWidth: 200, + divHeight: 200, + animator: null + } + DataTmp.animator = animator.create(options); }, Show() { - let options1 = { + let options1:AnimatorOptions = { duration: 1500, easing: "friction", delay: 0, @@ -308,19 +334,29 @@ export default { begin: 0, end: 400.0, }; + let DataTmp:DateT = { + divWidth: 200, + divHeight: 200, + animator: null + } try { - this.animator.reset(options1); + DataTmp.animator = animator.create(options1); + DataTmp.animator.reset(options1); } catch(error) { - console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`); + let message = (error as BusinessError).message + let code = (error as BusinessError).code + console.error(`Animator reset failed, error code: ${code}, message: ${message}.`); + } + let _this = DataTmp; + if(DataTmp.animator){ + DataTmp.animator.onframe = (value:number)=> { + _this.divWidth = value; + _this.divHeight = value; + }; + DataTmp.animator.play(); } - let _this = this; - this.animator.onframe = function(value) { - _this.divWidth = value; - _this.divHeight = value; - }; - this.animator.play(); } -} +})} ``` ![zh-cn_image_00007](figures/zh-cn_image_00007.gif) @@ -328,7 +364,7 @@ export default { ### 基于TS扩展的声明式开发范式 ```ts -import animator from '@ohos.animator'; +import animator, { AnimatorResult } from '@ohos.animator'; @Entry @Component @@ -459,16 +495,18 @@ struct AnimatorTest { .onClick(() => { if (this.flag) { this.flag = false - this.backAnimator.reset({ - duration: 5000, - easing: "ease-in", - delay: 0, - fill: "none", - direction: "normal", - iterations: 4, - begin: 100, - end: 300 - }) + if(this.backAnimator){ + this.backAnimator.reset({ + duration: 5000, + easing: "ease-in", + delay: 0, + fill: "none", + direction: "normal", + iterations: 4, + begin: 100, + end: 300 + }) + } } else { console.info(this.TAG, 'Animation not ended') } @@ -499,7 +537,7 @@ update(options: AnimatorOptions): void **示例:** -```js +```ts animator.update(options); ``` @@ -527,7 +565,8 @@ createAnimator(options: AnimatorOptions): AnimatorResult **示例:** -```js +```ts +import animator, { AnimatorOptions,AnimatorResult } from '@ohos.animator'; let options: AnimatorOptions = { // xxx.js文件中不需要强调显式类型AnimatorOptions duration: 1500, easing: "friction", diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md index d3d0fe0f8b41e5b368f8ab7f7247623955271540..3afa6875ef4da55e55ca6ac98f4203e53f2bb6ff 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -356,7 +356,7 @@ uiContext.showDatePickerDialog({ selected: selectedDate, onAccept: (value: DatePickerResult) => { // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期 - selectedDate.setFullYear(value.year, value.month, value.day) + selectedDate.setFullYear(Number(value.year), Number(value.month), Number(value.day)) console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) }, onCancel: () => { @@ -500,6 +500,7 @@ createAnimator(options: AnimatorOptions): AnimatorResult **示例:** ```ts +import { AnimatorOptions } from '@ohos.animator'; let options:AnimatorOptions = { duration: 1500, easing: "friction", @@ -558,6 +559,7 @@ registerFont(options: font.FontOptions): void **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; let font:Font = uiContext.getFont(); font.registerFont({ familyName: 'medium', @@ -581,7 +583,8 @@ getSystemFontList(): Array\ **示例:** ```ts -let font:Font = uiContext.getFont(); +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +let font:Font|undefined = uiContext.getFont(); font.getSystemFontList() ``` @@ -608,7 +611,8 @@ getFontByName(fontName: string): font.FontInfo **示例:** ```ts -let font:Font = uiContext.getFont(); +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +let font:Font|undefined = uiContext.getFont(); font.getFontByName('Sans Italic') ``` @@ -639,10 +643,11 @@ getRectangleById(id: string): componentUtils.ComponentInfo **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; let componentUtils:ComponentUtils = uiContext.getComponentUtils(); -let modePosition:componentUtils.ComponentInfo = componentUtils.getRectangleById("onClick"); -let localOffsetWidth:object = modePosition.size.width; -let localOffsetHeight:object = modePosition.size.height; +let modePosition = componentUtils.getRectangleById("onClick"); +let localOffsetWidth = modePosition.size.width; +let localOffsetHeight = modePosition.size.height; ``` ## UIInspector @@ -672,6 +677,7 @@ createComponentObserver(id: string): inspector.ComponentObserver **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; let inspector:UIInspector = uiContext.getUIInspector(); let listener = inspector.createComponentObserver('COMPONENT_ID'); ``` @@ -703,6 +709,7 @@ matchMediaSync(condition: string): mediaQuery.MediaQueryListener **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; let mediaquery: MediaQuery = uiContext.getMediaQuery(); let listener = mediaquery.matchMediaSync('(orientation: landscape)'); //监听横屏事件 ``` @@ -744,6 +751,8 @@ pushUrl(options: router.RouterOptions): Promise<void> **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); try { router.pushUrl({ @@ -790,6 +799,8 @@ pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): voi **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); router.pushUrl({ url: 'pages/routerpage2', @@ -801,7 +812,9 @@ router.pushUrl({ } }, (err: Error) => { if (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`pushUrl failed, code is ${code}, message is ${message}`); return; } console.info('pushUrl success'); @@ -842,9 +855,16 @@ pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void **示例:** ```ts -let router = uiContext.getRouter(); +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() try { - router.pushUrl({ + routerF.pushUrl({ url: 'pages/routerpage2', params: { data1: 'message', @@ -852,7 +872,7 @@ try { data3: [123, 456, 789] } } - }, router.RouterMode.Standard) + }, rtm.Standard) } catch (err) { let message = (err as BusinessError).message; let code = (err as BusinessError).code; @@ -889,8 +909,15 @@ pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncC **示例:** ```ts -let router = uiContext.getRouter(); -router.pushUrl({ +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() +routerF.pushUrl({ url: 'pages/routerpage2', params: { data1: 'message', @@ -898,9 +925,11 @@ router.pushUrl({ data3: [123, 456, 789] } } -}, router.RouterMode.Standard, (err) => { +}, rtm.Standard, (err) => { if (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`pushUrl failed, code is ${code}, message is ${message}`); return; } console.info('pushUrl success'); @@ -939,6 +968,8 @@ replaceUrl(options: router.RouterOptions): Promise<void> **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); try { router.replaceUrl({ @@ -981,6 +1012,8 @@ replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); router.replaceUrl({ url: 'pages/detail', @@ -989,7 +1022,9 @@ router.replaceUrl({ } }, (err: Error) => { if (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`replaceUrl failed, code is ${code}, message is ${message}`); return; } console.info('replaceUrl success'); @@ -1029,14 +1064,21 @@ replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<v **示例:** ```ts -let router = uiContext.getRouter(); +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() try { - router.replaceUrl({ + routerF.replaceUrl({ url: 'pages/detail', params: { data1: 'message' } - }, router.RouterMode.Standard) + }, rtm.Standard) } catch (err) { let message = (err as BusinessError).message; let code = (err as BusinessError).code; @@ -1072,15 +1114,24 @@ replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: Asy **示例:** ```ts -let router = uiContext.getRouter(); -router.replaceUrl({ +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() +routerF.replaceUrl({ url: 'pages/detail', params: { data1: 'message' } -}, router.RouterMode.Standard, (err: Error) => { +}, rtm.Standard, (err: Error) => { if (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`replaceUrl failed, code is ${code}, message is ${message}`); return; } console.info('replaceUrl success'); @@ -1120,6 +1171,8 @@ pushNamedRoute(options: router.NamedRouterOptions): Promise<void> **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); try { router.pushNamedRoute({ @@ -1166,6 +1219,8 @@ pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<vo **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); router.pushNamedRoute({ name: 'myPage', @@ -1177,7 +1232,9 @@ router.pushNamedRoute({ } }, (err: Error) => { if (err) { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); return; } console.info('pushNamedRoute success'); @@ -1217,9 +1274,16 @@ pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Pro **示例:** ```ts -let router = uiContext.getRouter(); +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() try { - router.pushNamedRoute({ + routerF.pushNamedRoute({ name: 'myPage', params: { data1: 'message', @@ -1227,7 +1291,7 @@ try { data3: [123, 456, 789] } } - }, router.RouterMode.Standard) + }, rtm.Standard) } catch (err) { let message = (err as BusinessError).message; let code = (err as BusinessError).code; @@ -1264,8 +1328,15 @@ pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, call **示例:** ```ts -let router = uiContext.getRouter(); -router.pushNamedRoute({ +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() +routerF.pushNamedRoute({ name: 'myPage', params: { data1: 'message', @@ -1273,9 +1344,11 @@ router.pushNamedRoute({ data3: [123, 456, 789] } } -}, router.RouterMode.Standard, (err: Error) => { +}, rtm.Standard, (err: Error) => { if (err) { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); return; } console.info('pushNamedRoute success'); @@ -1314,6 +1387,8 @@ replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); try { router.replaceNamedRoute({ @@ -1356,6 +1431,8 @@ replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback< **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router = uiContext.getRouter(); router.replaceNamedRoute({ name: 'myPage', @@ -1364,7 +1441,9 @@ router.replaceNamedRoute({ } }, (err: Error) => { if (err) { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); return; } console.info('replaceNamedRoute success'); @@ -1405,14 +1484,21 @@ replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): **示例:** ```ts -let router = uiContext.getRouter(); +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() try { - router.replaceNamedRoute({ + routerF.replaceNamedRoute({ name: 'myPage', params: { data1: 'message' } - }, router.RouterMode.Standard) + }, rtm.Standard) } catch (err) { let message = (err as BusinessError).message; let code = (err as BusinessError).code; @@ -1448,15 +1534,24 @@ replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, c **示例:** ```ts -let router = uiContext.getRouter(); -router.replaceNamedRoute({ +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; +import router from '@ohos.router'; +let routerF:Router = uiContext.getRouter(); +class routerTmp{ + Standard:router.RouterMode = router.RouterMode.Standard +} +let rtm:routerTmp = new routerTmp() +routerF.replaceNamedRoute({ name: 'myPage', params: { data1: 'message' } -}, router.RouterMode.Standard, (err: Error) => { +}, rtm.Standard, (err: Error) => { if (err) { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + let message = (err as BusinessError).message; + let code = (err as BusinessError).code; + console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); return; } console.info('replaceNamedRoute success'); @@ -1480,6 +1575,8 @@ back(options?: router.RouterOptions ): void **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router: Router = uiContext.getRouter(); router.back({url:'pages/detail'}); ``` @@ -1495,6 +1592,8 @@ clear(): void **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router: Router = uiContext.getRouter(); router.clear(); ``` @@ -1516,6 +1615,8 @@ getLength(): string **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router: Router = uiContext.getRouter(); let size = router.getLength(); console.log('pages stack size = ' + size); @@ -1538,6 +1639,8 @@ getState(): router.RouterState **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router: Router = uiContext.getRouter(); let page = router.getState(); console.log('current index = ' + page.index); @@ -1570,6 +1673,8 @@ showAlertBeforeBackPage(options: router.EnableAlertOptions): void **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router: Router = uiContext.getRouter(); try { router.showAlertBeforeBackPage({ @@ -1593,6 +1698,8 @@ hideAlertBeforeBackPage(): void **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router: Router = uiContext.getRouter(); router.hideAlertBeforeBackPage(); ``` @@ -1614,6 +1721,8 @@ getParams(): Object **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let router: Router = uiContext.getRouter(); router.getParams(); ``` @@ -1647,6 +1756,8 @@ showToast(options: promptAction.ShowToastOptions): void **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let promptAction: PromptAction = uiContext.getPromptAction(); try { promptAction.showToast({ @@ -1686,6 +1797,8 @@ showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<p **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; class buttonsMoabl { text: string = "" color: string = "" @@ -1713,7 +1826,9 @@ try { console.info('showDialog success callback, click button: ' + data.index); }); } catch (error) { - console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); + let message = (error as BusinessError).message; + let code = (error as BusinessError).code; + console.error(`showDialog args error code is ${code}, message is ${message}`); }; ``` @@ -1748,6 +1863,8 @@ showDialog(options: promptAction.ShowDialogOptions): Promise<promptAction.Sho **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let promptAction: PromptAction = uiContext.getPromptAction(); try { promptAction.showDialog({ @@ -1803,27 +1920,40 @@ showActionMenu(options: promptAction.ActionMenuOptions, callback:promptAction.Ac **示例:** ```ts -let promptAction: PromptAction = uiContext.getPromptAction(); +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import promptAction from '@ohos.promptAction'; +import { BusinessError } from '@ohos.base'; +class buttonsMoabl { + text: string = "" + color: string = "" +} +class dataR{ + err:Error = new Error; + data:promptAction.ActionMenuSuccessResponse | undefined = undefined; +} +let dataAMSR:dataR = new dataR() +let promptActionF: PromptAction = uiContext.getPromptAction(); try { - promptAction.showActionMenu({ - title: 'Title Info', - buttons: [ - { - text: 'item1', - color: '#666666' - }, - { - text: 'item2', - color: '#000000' - }, - ] - }, (err:Error, data:promptAction.ActionMenuSuccessResponse) => { - if (err) { - console.info('showActionMenu err: ' + err); - return; + if(dataAMSR.data){ + promptActionF.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666' + } as buttonsMoabl, + { + text: 'item2', + color: '#000000' + } as buttonsMoabl + ] + }, (dataAMSR.data)) + if (dataAMSR.err) { + console.info('showActionMenu err: ' + dataAMSR.err); + }else{ + console.info('showActionMenu success callback, click button: ' + dataAMSR.data.index); } - console.info('showActionMenu success callback, click button: ' + data.index); - }) + } } catch (error) { let message = (error as BusinessError).message; let code = (error as BusinessError).code; @@ -1862,6 +1992,8 @@ showActionMenu(options: promptAction.ActionMenuOptions): Promise<promptAction **示例:** ```ts +import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; +import { BusinessError } from '@ohos.base'; let promptAction: PromptAction = uiContext.getPromptAction(); try { promptAction.showActionMenu({ @@ -1888,4 +2020,4 @@ try { let code = (error as BusinessError).code; console.error(`showActionMenu args error code is ${code}, message is ${message}`); }; -``` +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md index f25d600c78371bacca408d0083ceca4e3d040b23..1fe4affe569684b0c4eb686f885ed35fc5915e4e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @@ -11,7 +11,7 @@ ## 导入模块 -```js +```ts import componentSnapshot from "@ohos.arkui.componentSnapshot"; ``` @@ -42,14 +42,14 @@ get(id: string, callback: AsyncCallback): void **示例:** -```js +```ts import componentSnapshot from '@ohos.arkui.componentSnapshot' import image from '@ohos.multimedia.image' @Entry @Component struct SnapshotExample { - @State pixmap: image.PixelMap = undefined + @State pixmap: image.PixelMap|undefined = undefined build() { Column() { @@ -108,14 +108,14 @@ get(id: string): Promise **示例:** -```js +```ts import componentSnapshot from '@ohos.arkui.componentSnapshot' import image from '@ohos.multimedia.image' @Entry @Component struct SnapshotExample { - @State pixmap: image.PixelMap = undefined + @State pixmap: image.PixelMap|undefined = undefined build() { Column() { @@ -203,7 +203,7 @@ struct OffscreenSnapshotExample { Column() { Button("click to generate offscreen UI snapshot") .onClick(() => { - componentSnapshot.createFromBuilder(this.RandomBuilder.bind(this), + componentSnapshot.createFromBuilder(this.RandomBuilder(), (error: Error, pixmap: image.PixelMap) => { this.pixmap = pixmap // save pixmap to file @@ -280,7 +280,7 @@ struct OffscreenSnapshotExample { Column() { Button("click to generate offscreen UI snapshot") .onClick(() => { - componentSnapshot.createFromBuilder(this.RandomBuilder.bind(this)) + componentSnapshot.createFromBuilder(this.RandomBuilder()) .then((pixmap: image.PixelMap) => { this.pixmap = pixmap // save pixmap to file diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md index 6276e519877c332d7076824d78c6b0b70006cdbc..9ff05249e29f5414441f0de59ae288d4384dd99c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md @@ -37,7 +37,7 @@ executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: DragInfo, callback: ```ts import dragController from "@ohos.arkui.dragController" -import UDC from '@ohos.data.unifiedDataChannel'; +import UDMF from '@ohos.data.UDMF'; @Entry @Component @@ -57,18 +57,23 @@ struct DragControllerPage { .onTouch((event?:TouchEvent) => { if(event){ if (event.type == TouchType.Down) { - let text:object = new UDMF.Text() - let unifiedData:object = new UDMF.UnifiedData(text) + let text = new UDMF.Text() + let unifiedData = new UDMF.UnifiedData(text) let dragInfo: dragController.DragInfo = { pointerId: 0, data: unifiedData, extraParams: '' } - dragController.executeDrag(this.DraggingBuilder.bind(this), dragInfo, (err, {event, extraParams}) => { - if (event.getResult() == DragResult.DRAG_SUCCESSFUL) { + class tmp{ + event:DragResult|undefined = undefined + extraParams:string = '' + } + let eve:tmp = new tmp() + dragController.executeDrag(this.DraggingBuilder(), dragInfo, (err, eve) => { + if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { // ... - } else if (event.getResult() == DragResult.DRAG_FAILED) { + } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { // ... } }) @@ -105,9 +110,9 @@ executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: DragInfo): Promise&l ```ts import dragController from "@ohos.arkui.dragController" -import UDC from '@ohos.data.unifiedDataChannel'; import componentSnapshot from '@ohos.arkui.componentSnapshot'; import image from '@ohos.multimedia.image'; +import UDMF from '@ohos.data.UDMF'; @Entry @Component @@ -138,31 +143,36 @@ struct DragControllerPage { .onTouch((event?:TouchEvent) => { if(event){ if (event.type == TouchType.Down) { - let text:object = new UDMF.Text() - let unifiedData:object = new UDMF.UnifiedData(text) + let text = new UDMF.Text() + let unifiedData = new UDMF.UnifiedData(text) let dragInfo: dragController.DragInfo = { pointerId: 0, data: unifiedData, extraParams: '' } - componentSnapshot.createFromBuilder(this.PixmapBuilder.bind(this)).then((pix: image.PixelMap) => { + componentSnapshot.createFromBuilder(this.PixmapBuilder()).then((pix: image.PixelMap) => { this.pixmap = pix; let dragItemInfo: DragItemInfo = { pixelMap: this.pixmap, - builder: this.DraggingBuilder.bind(this), + builder: this.DraggingBuilder(), extraInfo: "DragItemInfoTest" } + class tmp{ + event:DragResult|undefined = undefined + extraParams:string = '' + } + let eve:tmp = new tmp() dragController.executeDrag(dragItemInfo, dragInfo) - .then(({event, extraParams}) => { - if (event.getResult() == DragResult.DRAG_SUCCESSFUL) { + .then((eve) => { + if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { // ... - } else if (event.getResult() == DragResult.DRAG_FAILED) { + } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { // ... } }) - .catch((err) => { + .catch((err:Error) => { }) }) } diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md index fe16d841e7cb8d91cb9143ab9e8a04d4be6c8fad..3e52e9de9c7f18b494eeeed96d0411d0ab8f0925 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @@ -10,7 +10,7 @@ ## 导入模块 -```js +```ts import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor'; ``` @@ -80,10 +80,11 @@ getPixelMap(): image.PixelMap; **示例:** ```ts +import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor' let resManager = getContext().resourceManager let pixmap: DrawableDescriptor = (resManager.getDrawableDescriptor($r('app.media.icon') .id)) as DrawableDescriptor; -let pixmapNew: DrawableDescriptor = pixmap.getPixelMap() +let pixmapNew: object = pixmap.getPixelMap() ``` ## LayeredDrawableDescriptor.getPixelMap @@ -101,10 +102,11 @@ getPixelMap(): image.PixelMap; **示例:** ```ts +import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor' let resManager = getContext().resourceManager let pixmap: LayeredDrawableDescriptor = (resManager.getDrawableDescriptor($r('app.media.icon') .id)) as LayeredDrawableDescriptor; -let pixmapNew: LayeredDrawableDescriptor = pixmap.getPixelMap() +let pixmapNew: object = pixmap.getPixelMap() ``` ## LayeredDrawableDescriptor.getForeground @@ -122,10 +124,11 @@ getForeground(): DrawableDescriptor; **示例:** ```ts +import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor' let resManager = getContext().resourceManager let drawable: LayeredDrawableDescriptor = (resManager.getDrawableDescriptor($r('app.media.icon') .id)) as LayeredDrawableDescriptor; -let drawableNew: LayeredDrawableDescriptor =drawable.getForeground() +let drawableNew: object =drawable.getForeground() ``` ## LayeredDrawableDescriptor.getBackground @@ -143,10 +146,11 @@ getBackground(): DrawableDescriptor; **示例:** ```ts +import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor' let resManager = getContext().resourceManager let drawable: LayeredDrawableDescriptor = (resManager.getDrawableDescriptor($r('app.media.icon') .id)) as LayeredDrawableDescriptor; -let drawableNew: LayeredDrawableDescriptor =drawable.getBackground() +let drawableNew: object =drawable.getBackground() ``` ## LayeredDrawableDescriptor.getMask @@ -164,10 +168,11 @@ getMask(): DrawableDescriptor; **示例:** ```ts +import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor' let resManager = getContext().resourceManager let drawable: LayeredDrawableDescriptor = (resManager.getDrawableDescriptor($r('app.media.icon') .id)) as LayeredDrawableDescriptor; -let drawableNew: LayeredDrawableDescriptor =drawable.getMask() +let drawableNew: object =drawable.getMask() ``` ## LayeredDrawableDescriptor.getMaskClipPath static getMaskClipPath(): string @@ -184,6 +189,7 @@ LayeredDrawableDescriptor的静态方法,获取系统内置的裁切路径参 **示例:** ```ts +import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor' Image($r('app.media.icon')) .width('200px').height('200px') .clip(new Path({commands:LayeredDrawableDescriptor.getMaskClipPath()})) diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-inspector.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-inspector.md index c31e46948a53de659fb1d64d0160a116d993247a..2f987e9e4cfec567e811503cd570d329f6f56b20 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-inspector.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-inspector.md @@ -10,7 +10,7 @@ ## 导入模块 -```js +```ts import inspector from '@ohos.arkui.inspector' ``` @@ -36,8 +36,8 @@ createComponentObserver(id: string): ComponentObserver **示例:** -```js -let listener = inspector.createComponentObserver('COMPONENT_ID'); //监听id为COMPONENT_ID的组件回调事件 +```ts +let listener:inspector = inspector.createComponentObserver('COMPONENT_ID'); //监听id为COMPONENT_ID的组件回调事件 ``` ## ComponentObserver @@ -129,19 +129,17 @@ off(type: 'draw', callback?: () => void): void listener:inspector.ComponentObserver = inspector.createComponentObserver('IMAGE_ID') aboutToAppear() { - let FuncLayout = this.onLayoutComplete.bind(this) // bind current js instance - let FuncDraw = this.onDrawComplete.bind(this) // bind current js instance + let onLayoutComplete:()=>void=():void=>{ + // do something here + } + let onDrawComplete:()=>void=():void=>{ + // do something here + } + let FuncLayout = onLayoutComplete // bind current js instance + let FuncDraw = onDrawComplete // bind current js instance this.listener.on('layout', FuncLayout) this.listener.on('draw', FuncDraw) } - - onLayoutComplete() { - // do something here - } - - onDrawComplete() { - // do something here - } } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 3284f0899bdf2e2f3c3a269f349c8383184a923a..51c857fc8bfc18b193f5121c2c51e739ca757f65 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -17,7 +17,7 @@ ## 导入模块 -```js +```ts import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` @@ -47,7 +47,7 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen **示例**: - ```js + ```ts import backgroundTaskManager from '@ohos.backgroundTaskManager'; let myReason = 'test requestSuspendDelay'; @@ -79,11 +79,11 @@ getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): **示例**: - ```js + ```ts import backgroundTaskManager from '@ohos.backgroundTaskManager'; let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); - backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId, (err, res) => { + backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId, (err: BusinessError, res: number) => { if(err) { console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code); } else { @@ -115,7 +115,7 @@ getRemainingDelayTime(requestId: number): Promise<number> **示例**: -```js +```ts let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then((res:number) => { console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); @@ -141,7 +141,7 @@ cancelSuspendDelay(requestId: number): void **示例**: - ```js + ```ts let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId); ``` @@ -267,7 +267,7 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want **示例**: -FA模型示例: +FA模型示例(需使用js代码开发): ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; @@ -348,7 +348,7 @@ stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): vo **示例**: -FA模型示例: +FA模型示例(需使用js代码开发): ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; diff --git a/zh-cn/application-dev/reference/apis/js-apis-cooperate.md b/zh-cn/application-dev/reference/apis/js-apis-cooperate.md index 2bc41d10e707d58fad81d7c56f43e42ca70ac810..14738c3a7a4f79255c739b161bc7a95b8bd32c17 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-cooperate.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cooperate.md @@ -108,8 +108,8 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCal | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 4400001 | 当调用键鼠穿越接口传入无效的设备描述符参数时,系统会产生此错误码。 | -| 4400002 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | +| 4400001 | Incorrect descriptor for the target device. | +| 4400002 | Screen hop failed. | **示例**: @@ -158,8 +158,8 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 4400001 | 当调用键鼠穿越接口传入无效的设备描述符参数时,系统会产生此错误码。 | -| 4400002 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | +| 4400001 | Incorrect descriptor for the target device. | +| 4400002 | Screen hop failed. | **示例**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-devicestatus-cooperate.md b/zh-cn/application-dev/reference/apis/js-apis-devicestatus-cooperate.md index 980c45ab910b34c49161113b0c86cdcdf0ba7f67..6423fde96b5bfa7b271d822ed006289288be9745 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-devicestatus-cooperate.md +++ b/zh-cn/application-dev/reference/apis/js-apis-devicestatus-cooperate.md @@ -156,7 +156,7 @@ activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 20900001 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | +| 20900001 | Operation failed. | **示例**: @@ -205,7 +205,7 @@ activate(targetNetworkId: string, inputDeviceId: number): Promise<void>; | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 20900001 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | +| 20900001 | Operation failed. | **示例**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md b/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md index e6f056289ace23b20e9e63ebb62f7f907a89277f..7ac275b6af0199f875f315546092cde5d4c9b778 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @@ -10,7 +10,7 @@ ## 导入模块 -```js +```ts import hiSysEvent from '@ohos.hiSysEvent'; ``` @@ -73,26 +73,29 @@ write(info: SysEventInfo, callback: AsyncCallback<void>): void **示例:** -```js +```ts import hiSysEvent from '@ohos.hiSysEvent'; +import { BusinessError } from '@ohos.base'; try { - hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } - }, (err, val) => { - // do something here. - }) -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + let customizedParams: Record = { + 'PID': 487, + 'UID': 103, + 'PACKAGE_NAME': "com.ohos.hisysevent.test", + 'PROCESS_NAME': "syseventservice", + 'MSG': "no msg." + }; + let eventInfo: hiSysEvent.SysEventInfo = { + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: customizedParams + }; + hiSysEvent.write(eventInfo, (err: BusinessError, val: number) => { + // do something here. + }); +} catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` @@ -134,32 +137,35 @@ write(info: SysEventInfo): Promise<void> **示例:** -```js +```ts import hiSysEvent from '@ohos.hiSysEvent'; +import { BusinessError } from '@ohos.base'; try { - hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } - }).then( - (val) => { - // do something here. - } - ).catch( - (err) => { - // do something here. - } - ) -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + let customizedParams: Record = { + 'PID': 487, + 'UID': 103, + 'PACKAGE_NAME': "com.ohos.hisysevent.test", + 'PROCESS_NAME': "syseventservice", + 'MSG': "no msg." + }; + let eventInfo: hiSysEvent.SysEventInfo = { + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: customizedParams + }; + hiSysEvent.write(eventInfo).then( + (val: number) => { + // do something here. + } + ).catch( + (err: BusinessError) => { + console.error(`error code: ${err.code}, error msg: ${err.message}`); + } + ) +} catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` @@ -227,27 +233,29 @@ addWatcher(watcher: Watcher): void **示例:** -```js +```ts import hiSysEvent from '@ohos.hiSysEvent'; - -let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } +import { BusinessError } from '@ohos.base'; + +let watchRules: hiSysEvent.WatchRule[] = [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + } as hiSysEvent.WatchRule]; +let watcher: hiSysEvent.Watcher = { + rules: watchRules, + onEvent: (info: hiSysEvent.SysEventInfo) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } } try { - hiSysEvent.addWatcher(watcher) -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + hiSysEvent.addWatcher(watcher) +} catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` @@ -277,28 +285,30 @@ removeWatcher(watcher: Watcher): void **示例:** -```js +```ts import hiSysEvent from '@ohos.hiSysEvent'; - -let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } +import { BusinessError } from '@ohos.base'; + +let watchRules: hiSysEvent.WatchRule[] = [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + } as hiSysEvent.WatchRule ] +let watcher: hiSysEvent.Watcher = { + rules: watchRules, + onEvent: (info: hiSysEvent.SysEventInfo) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } } try { - hiSysEvent.addWatcher(watcher) - hiSysEvent.removeWatcher(watcher) -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + hiSysEvent.addWatcher(watcher) + hiSysEvent.removeWatcher(watcher) +} catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` @@ -370,41 +380,48 @@ query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): void **示例:** -```js +```ts import hiSysEvent from '@ohos.hiSysEvent'; +import { BusinessError } from '@ohos.base'; try { - hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } - }, (err, val) => { - // do something here. - }) - hiSysEvent.query({ - beginTime: -1, - endTime: -1, - maxEvents: 5, - }, [{ - domain: "RELIABILITY", - names: ["STACK"], - }], { - onQuery: function (infos) { - // do something here. - }, - onComplete: function(reason, total) { - // do something here. - } - }) -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + let customizedParams: Record = { + 'PID': 487, + 'UID': 103, + 'PACKAGE_NAME': "com.ohos.hisysevent.test", + 'PROCESS_NAME': "syseventservice", + 'MSG': "no msg." + }; + let eventInfo: hiSysEvent.SysEventInfo = { + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: customizedParams + }; + hiSysEvent.write(eventInfo, (err: BusinessError, val: number) => { + // do something here. + }) + + let queryArg: hiSysEvent.QueryArg = { + beginTime: -1, + endTime: -1, + maxEvents: 5, + }; + let queryRules: hiSysEvent.QueryRule[] = [{ + domain: "RELIABILITY", + names: ["STACK"], + } as hiSysEvent.QueryRule] + let querier: hiSysEvent.Querier = { + onQuery: (infos: hiSysEvent.SysEventInfo[]) => { + // do something here. + }, + onComplete: (reason: number, total: number) => { + // do something here. + } + } + hiSysEvent.query(queryArg, queryRules, querier) +} catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` @@ -443,50 +460,55 @@ exportSysEvents(queryArg: QueryArg, rules: QueryRule[]): number **示例:** -``` +```ts import hiSysEvent from '@ohos.hiSysEvent'; import fs from '@ohos.file.fs'; +import { BusinessError } from '@ohos.base'; try { - hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } - }, (err, val) => { - // do something here. - }) - - let time = hiSysEvent.exportSysEvents({ - beginTime: -1, - endTime: -1, - maxEvents: 1, - }, [{ - domain: "RELIABILITY", - names: ["STACK"], - }]) - console.log(`receive export task time is : ${time}`); - - // 延迟读取本次导出的事件 - setTimeout(function() { - let eventDir = '/data/storage/el2/base/cache/hiview/event'; - let filenames = fs.listFileSync(eventDir); - for (let i = 0; i < filenames.length; i++) { - if (filenames[i].indexOf(time.toString()) != -1) { - let res = fs.readTextSync(eventDir + '/' + filenames[i]); - let events = JSON.parse('[' + res.slice(0, res.length - 1) + ']'); - console.log("read file end, events is :" + JSON.stringify(events)); - } - } - }, 10000) -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + let customizedParams: Record = { + 'PID': 487, + 'UID': 103, + 'PACKAGE_NAME': "com.ohos.hisysevent.test", + 'PROCESS_NAME': "syseventservice", + 'MSG': "no msg." + }; + let eventInfo: hiSysEvent.SysEventInfo = { + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: customizedParams + }; + hiSysEvent.write(eventInfo, (err: BusinessError, val: number) => { + // do something here. + }) + + let queryArg: hiSysEvent.QueryArg = { + beginTime: -1, + endTime: -1, + maxEvents: 1, + } + let queryRules: hiSysEvent.QueryRule[] = [{ + domain: "RELIABILITY", + names: ["STACK"], + } as hiSysEvent.QueryRule] + let time = hiSysEvent.exportSysEvents(queryArg, queryRules) + console.log(`receive export task time is : ${time}`); + + // 延迟读取本次导出的事件 + setTimeout(() => { + let eventDir = '/data/storage/el2/base/cache/hiview/event'; + let filenames = fs.listFileSync(eventDir); + for (let i = 0; i < filenames.length; i++) { + if (filenames[i].indexOf(time.toString()) != -1) { + let res = fs.readTextSync(eventDir + '/' + filenames[i]); + let events: string = JSON.parse('[' + res.slice(0, res.length - 1) + ']'); + console.log("read file end, events is :" + JSON.stringify(events)); + } + } + }, 10000) +} catch catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` @@ -523,45 +545,51 @@ subscribe(rules: QueryRule[]): number **示例:** -``` +```ts import hiSysEvent from '@ohos.hiSysEvent'; import fs from '@ohos.file.fs'; +import { BusinessError } from '@ohos.base'; try { - hiSysEvent.subscribe([{ - domain: "RELIABILITY", - names: ["STACK"], - },{ - domain: "BUNDLE_MANAGER", - names: ["BUNDLE_UNINSTALL"], - }]) - hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } - }, (err, val) => { - // do something here. - }) - - // 延迟读取订阅的事件 - setTimeout(function() { - let eventDir = '/data/storage/el2/base/cache/hiview/event'; - let filenames = fs.listFileSync(eventDir); - for (let i = 0; i < filenames.length; i++) { - let res = fs.readTextSync(eventDir + '/' + filenames[i]); - let events = JSON.parse('[' + res.slice(0, res.length - 1) + ']'); - console.log("read file end, events is :" + JSON.stringify(events)); - } - }, 10000) -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + let rules: hiSysEvent.QueryRule[] = [{ + domain: "RELIABILITY", + names: ["STACK"], + } as hiSysEvent.QueryRule, + { + domain: "BUNDLE_MANAGER", + names: ["BUNDLE_UNINSTALL"], + } as hiSysEvent.QueryRule]; + hiSysEvent.subscribe(rules) + + let customizedParams: Record = { + 'PID': 487, + 'UID': 103, + 'PACKAGE_NAME': "com.ohos.hisysevent.test", + 'PROCESS_NAME': "syseventservice", + 'MSG': "no msg." + }; + let eventInfo: hiSysEvent.SysEventInfo = { + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: customizedParams + }; + hiSysEvent.write(eventInfo, (err: BusinessError, val: number) => { + // do something here. + }) + + // 延迟读取订阅的事件 + setTimeout(() => { + let eventDir = '/data/storage/el2/base/cache/hiview/event'; + let filenames = fs.listFileSync(eventDir); + for (let i = 0; i < filenames.length; i++) { + let res = fs.readTextSync(eventDir + '/' + filenames[i]); + let events: string = JSON.parse('[' + res.slice(0, res.length - 1) + ']'); + console.log("read file end, events is :" + JSON.stringify(events)); + } + }, 10000) +} catch catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` @@ -585,20 +613,23 @@ unsubscribe(): void **示例:** -``` +```ts import hiSysEvent from '@ohos.hiSysEvent'; +import { BusinessError } from '@ohos.base'; try { - hiSysEvent.subscribe([{ - domain: "RELIABILITY", - names: ["STACK"], - },{ - domain: "BUNDLE_MANAGER", - names: ["BUNDLE_UNINSTALL","BUNDLE_INSTALL"], - }]) - hiSysEvent.unsubscribe(); -} catch (error) { - console.error(`error code: ${error.code}, error msg: ${error.message}`); + let rules: hiSysEvent.QueryRule[] = [{ + domain: "RELIABILITY", + names: ["STACK"], + } as hiSysEvent.QueryRule, + { + domain: "BUNDLE_MANAGER", + names: ["BUNDLE_UNINSTALL"], + } as hiSysEvent.QueryRule]; + hiSysEvent.subscribe(rules) + hiSysEvent.unsubscribe(); +} catch (err) { + console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-hitracechain.md b/zh-cn/application-dev/reference/apis/js-apis-hitracechain.md index fafe10d136c0097d078f605a1a60aa4832887e5e..2427431c0a5504d9862cc373f7e96954dc9f1397 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hitracechain.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @@ -8,7 +8,7 @@ ## 导入模块 -```js +```ts import hiTraceChain from '@ohos.hiTraceChain'; ``` @@ -93,7 +93,7 @@ begin(name: string, flags?: number): HiTraceId **示例:** -```js +```ts let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC | hiTraceChain.HiTraceFlag.DONOT_CREATE_SPAN); ``` @@ -113,7 +113,7 @@ end(id: HiTraceId): void **示例:** -```js +```ts let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // 若干业务逻辑完成后,结束跟踪。 hiTraceChain.end(asyncTraceId); @@ -135,7 +135,7 @@ getId(): HiTraceId **示例:** -```js +```ts let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // 若干业务逻辑完成后,获取当前HiTraceId。 let curTraceId = hiTraceChain.getId(); @@ -157,10 +157,11 @@ setId(id: HiTraceId): void **示例:** -```js -let asyncTraceId; +```ts +let asyncTraceId: hiTraceChain.HiTraceId; +hiTraceChain.end(asyncTraceId); let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); -// 若干业务逻辑完成后,设置当前HiTraceId。 +// 若干业务逻辑完成后,将之前的traceId设置为当前traceId。 hiTraceChain.setId(asyncTraceId); ``` @@ -174,7 +175,7 @@ clearId(): void **示例:** -```js +```ts let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // 若干业务逻辑完成后,清除当前HiTraceId。 hiTraceChain.clearId(); @@ -196,7 +197,7 @@ createSpan(): HiTraceId **示例:** -```js +```ts let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // 若干业务逻辑完成后,创建跟踪分支。 let spanTraceId = hiTraceChain.createSpan(); @@ -221,7 +222,7 @@ tracepoint(mode: HiTraceCommunicationMode, type: HiTraceTracepointType, id: HiTr **示例:** -```js +```ts let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC | hiTraceChain.HiTraceFlag.DONOT_CREATE_SPAN); // 若干业务逻辑完成后,触发信息埋点操作。 hiTraceChain.tracepoint(hiTraceChain.HiTraceCommunicationMode.THREAD, hiTraceChain.HiTraceTracepointType.SS, asyncTraceId, "Just a example"); @@ -249,7 +250,7 @@ isValid(id: HiTraceId): boolean **示例:** -```js +```ts let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); let traceIdIsvalid = hiTraceChain.isValid(traceId); ``` @@ -277,7 +278,7 @@ isFlagEnabled(id: HiTraceId, flag: HiTraceFlag): boolean **示例:** -```js +```ts let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC); // enabledDoNotCreateSpanFlag为true let enabledDoNotCreateSpanFlag = hiTraceChain.isFlagEnabled(asyncTraceId, hiTraceChain.HiTraceFlag.INCLUDE_ASYNC); @@ -300,7 +301,7 @@ enableFlag(id: HiTraceId, flag: HiTraceFlag): void **示例:** -```js +```ts let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC); hiTraceChain.enableFlag(asyncTraceId, hiTraceChain.HiTraceFlag.DONOT_CREATE_SPAN); // enabledDoNotCreateSpanFlag为true diff --git a/zh-cn/application-dev/reference/apis/js-apis-image.md b/zh-cn/application-dev/reference/apis/js-apis-image.md index 145ac36d239a216bbddfcb366de171937455b010..863db6376bb4209ff09da5c8744a55564ad0c450 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-image.md +++ b/zh-cn/application-dev/reference/apis/js-apis-image.md @@ -36,13 +36,14 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\ { - console.log('Succeeded in creating pixelmap.'); -}).catch(error => { - console.log('Failed to create pixelmap.'); +import {BusinessError} from '@ohos.base' +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap : image.PixelMap) => { + console.log('Succeeded in creating pixelmap.'); +}).catch((error : BusinessError) => { + console.log('Failed to create pixelmap.'); }) ``` @@ -65,10 +66,10 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: As **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (error, pixelmap) => { +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (error, pixelmap : image.PixelMap) => { if(error) { console.log('Failed to create pixelmap.'); } else { @@ -112,10 +113,11 @@ readPixelsToBuffer(dst: ArrayBuffer): Promise\ **示例:** ```js -const readBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +import {BusinessError} from '@ohos.base' +const readBuffer : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 pixelmap.readPixelsToBuffer(readBuffer).then(() => { console.log('Succeeded in reading image pixel data.'); //符合条件则进入 -}).catch(error => { +}).catch((error : BusinessError) => { console.log('Failed to read image pixel data.'); //不符合条件则进入 }) ``` @@ -138,7 +140,7 @@ readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\): void **示例:** ```js -const readBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +const readBuffer : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 pixelmap.readPixelsToBuffer(readBuffer, (err, res) => { if(err) { console.log('Failed to read image pixel data.'); //不符合条件则进入 @@ -171,7 +173,8 @@ readPixels(area: PositionArea): Promise\ **示例:** ```js -const area = { +import {BusinessError} from '@ohos.base' +const area : image.PositionArea = { pixels: new ArrayBuffer(8), offset: 0, stride: 8, @@ -179,7 +182,7 @@ const area = { } pixelmap.readPixels(area).then(() => { console.log('Succeeded in reading the image data in the area.'); //符合条件则进入 -}).catch(error => { +}).catch((error : BusinessError) => { console.log('Failed to read the image data in the area.'); //不符合条件则进入 }) ``` @@ -202,14 +205,14 @@ readPixels(area: PositionArea, callback: AsyncCallback\): void **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (err, pixelmap) => { +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err, pixelmap : image.PixelMap) => { if(pixelmap == undefined){ console.info('createPixelMap failed.'); } else { - const area = { pixels: new ArrayBuffer(8), + const area : image.PositionArea = { pixels: new ArrayBuffer(8), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }}; @@ -243,20 +246,21 @@ writePixels(area: PositionArea): Promise\ **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +import {BusinessError} from '@ohos.base' +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts) - .then( pixelmap => { + .then( (pixelmap : image.PixelMap) => { if (pixelmap == undefined) { console.info('createPixelMap failed.'); } - const area = { pixels: new ArrayBuffer(8), + const area : image.PositionArea = { pixels: new ArrayBuffer(8), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 } } - let bufferArr = new Uint8Array(area.pixels); + let bufferArr : Uint8Array = new Uint8Array(area.pixels); for (var i = 0; i < bufferArr.length; i++) { bufferArr[i] = i + 1; } @@ -264,7 +268,7 @@ image.createPixelMap(color, opts) pixelmap.writePixels(area).then(() => { console.info('Succeeded to write pixelmap into the specified area.'); }) - }).catch(error => { + }).catch((error : BusinessError) => { console.log('error: ' + error); }) ``` @@ -287,12 +291,12 @@ writePixels(area: PositionArea, callback: AsyncCallback\): void **示例:** ```js -const area = { pixels: new ArrayBuffer(8), +const area : image.PositionArea = { pixels: new ArrayBuffer(8), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 } } -let bufferArr = new Uint8Array(area.pixels); +let bufferArr : Uint8Array = new Uint8Array(area.pixels); for (var i = 0; i < bufferArr.length; i++) { bufferArr[i] = i + 1; } @@ -328,14 +332,15 @@ writeBufferToPixels(src: ArrayBuffer): Promise\ **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let bufferArr = new Uint8Array(color); +import {BusinessError} from '@ohos.base' +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); for (var i = 0; i < bufferArr.length; i++) { bufferArr[i] = i + 1; } pixelmap.writeBufferToPixels(color).then(() => { console.log("Succeeded in writing data from a buffer to a PixelMap."); -}).catch((err) => { +}).catch((error : BusinessError) => { console.error("Failed to write data from a buffer to a PixelMap."); }) ``` @@ -358,8 +363,8 @@ writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\): void **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let bufferArr = new Uint8Array(color); +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); for (var i = 0; i < bufferArr.length; i++) { bufferArr[i] = i + 1; } @@ -390,13 +395,13 @@ getImageInfo(): Promise\ **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } -image.createPixelMap(color, opts).then(pixelmap => { +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let opts : image.InitializationOptions = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } +image.createPixelMap(color, opts).then((pixelmap : image.PixelMap) => { if (pixelmap == undefined) { console.error("Failed to obtain the image pixel map information."); } - pixelmap.getImageInfo().then(imageInfo => { + pixelmap.getImageInfo().then((imageInfo : image.ImageInfo) => { if (imageInfo == undefined) { console.error("Failed to obtain the image pixel map information."); } @@ -424,13 +429,13 @@ getImageInfo(callback: AsyncCallback\): void **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (err, pixelmap) => { +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err, pixelmap : image.PixelMap) => { if (pixelmap == undefined) { console.error("Failed to obtain the image pixel map information."); } - pixelmap.getImageInfo((err, imageInfo) => { + pixelmap.getImageInfo((err, imageInfo : image.ImageInfo) => { if (imageInfo == undefined) { console.error("Failed to obtain the image pixel map information."); } @@ -458,11 +463,11 @@ getBytesNumberPerRow(): number **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (err,pixelmap) => { - let rowCount = pixelmap.getBytesNumberPerRow(); +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err,pixelmap : image.PixelMap) => { + let rowCount : number = pixelmap.getBytesNumberPerRow(); }) ``` @@ -483,7 +488,7 @@ getPixelBytesNumber(): number **示例:** ```js -let pixelBytesNumber = pixelmap.getPixelBytesNumber(); +let pixelBytesNumber : number = pixelmap.getPixelBytesNumber(); ``` ### getDensity9+ @@ -503,7 +508,7 @@ getDensity():number **示例:** ```js -let getDensity = pixelmap.getDensity(); +let getDensity : number = pixelmap.getDensity(); ``` ### opacity9+ @@ -602,7 +607,7 @@ createAlphaPixelmap(callback: AsyncCallback\): void **示例:** ```js -pixelmap.createAlphaPixelmap((err, alphaPixelMap) => { +pixelmap.createAlphaPixelmap((err, alphaPixelMap : image.PixelMap) => { if (alphaPixelMap == undefined) { console.info('Failed to obtain new pixel map.'); } else { @@ -983,16 +988,16 @@ class MySequence { return true; } async unmarshalling(messageSequence) { - let pixelParcel = await image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}); - await pixelParcel.unmarshalling(messageSequence).then(async (pixelMap) => { + let pixelParcel : image.PixelMap = await image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}); + await pixelParcel.unmarshalling(messageSequence).then(async (pixelMap : image.PixelMap) => { this.pixel_map = pixelMap; }) return true; } } async function Demo() { - let parcelable = new MySequence(pixelmap); - let data = rpc.MessageSequence.create(); + let parcelable : MySequence = new MySequence(pixelmap); + let data : rpc.MessageSequence = rpc.MessageSequence.create(); data.writeParcelable(parcelable); } ``` @@ -1042,8 +1047,8 @@ class MySequence { return true; } async unmarshalling(messageSequence) { - let pixelParcel = await image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}); - await pixelParcel.unmarshalling(messageSequence).then(async (pixelMap) => { + let pixelParcel : image.PixelMap = await image.createPixelMap(new ArrayBuffer(96), {size: { height:4, width: 6}}); + await pixelParcel.unmarshalling(messageSequence).then(async (pixelMap : image.PixelMap) => { this.pixel_map = pixelMap; }) return true; @@ -1051,8 +1056,8 @@ class MySequence { } async function Demo() { let pixel_map = undefined; - let ret = new MySequence(pixel_map); - let data = rpc.MessageSequence.create(); + let ret : MySequence = new MySequence(pixel_map); + let data : rpc.MessageSequence = rpc.MessageSequence.create(); await data.readParcelable(ret); } ``` @@ -1074,9 +1079,10 @@ release():Promise\ **示例:** ```js +import {BusinessError} from '@ohos.base' pixelmap.release().then(() => { console.log('Succeeded in releasing pixelmap object.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('Failed to release pixelmap object.'); }) ``` @@ -1127,18 +1133,18 @@ createImageSource(uri: string): ImageSource ```js //Stage模型 -const context = getContext(this); -const path = context.cacheDir + "/test.jpg"; -const imageSourceApi = image.createImageSource(path); +const context : Context = getContext(this); +const path : string= context.cacheDir + "/test.jpg"; +const imageSourceApi : image.ImageSource = image.createImageSource(path); ``` ```js //FA模型 import featureAbility from '@ohos.ability.featureAbility'; -const context = featureAbility.getContext(); -const path = context.getCacheDir() + "/test.jpg"; -const imageSourceApi = image.createImageSource(path); +const context : Context = featureAbility.getContext(); +const path : string= context.getCacheDir() + "/test.jpg"; +const imageSourceApi : image.ImageSource = image.createImageSource(path); ``` ## image.createImageSource9+ @@ -1165,8 +1171,8 @@ createImageSource(uri: string, options: SourceOptions): ImageSource **示例:** ```js -var sourceOptions = { sourceDensity: 120 }; -let imageSource = image.createImageSource('test.png', sourceOptions); +var sourceOptions : image.SourceOptions = { sourceDensity: 120 }; +let imageSource : image.ImageSource = image.createImageSource('test.png', sourceOptions); ``` ## image.createImageSource7+ @@ -1192,7 +1198,7 @@ createImageSource(fd: number): ImageSource **示例:** ```js -const imageSourceApi = image.createImageSource(0); +const imageSourceApi : image.ImageSource = image.createImageSource(0); ``` ## image.createImageSource9+ @@ -1219,8 +1225,8 @@ createImageSource(fd: number, options: SourceOptions): ImageSource **示例:** ```js -var sourceOptions = { sourceDensity: 120 }; -const imageSourceApi = image.createImageSource(0, sourceOptions); +var sourceOptions : image.SourceOptions = { sourceDensity: 120 }; +const imageSourceApi : image.ImageSource = image.createImageSource(0, sourceOptions); ``` ## image.createImageSource9+ @@ -1240,8 +1246,8 @@ createImageSource(buf: ArrayBuffer): ImageSource **示例:** ```js -const buf = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -const imageSourceApi = image.createImageSource(buf); +const buf : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +const imageSourceApi : image.ImageSource = image.createImageSource(buf); ``` ## image.createImageSource9+ @@ -1268,8 +1274,8 @@ createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource **示例:** ```js -const data = new ArrayBuffer(112); -const imageSourceApi = image.createImageSource(data); +const data : ArrayBuffer= new ArrayBuffer(112); +const imageSourceApi : image.ImageSource = image.createImageSource(data); ``` ## image.CreateIncrementalSource9+ @@ -1295,8 +1301,8 @@ CreateIncrementalSource(buf: ArrayBuffer): ImageSource **示例:** ```js -const buf = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); +const buf : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +const imageSourceIncrementalSApi : image.ImageSource = image.CreateIncrementalSource(buf); ``` ## image.CreateIncrementalSource9+ @@ -1323,8 +1329,8 @@ CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource **示例:** ```js -const buf = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); +const buf : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +const imageSourceIncrementalSApi : image.ImageSource = image.CreateIncrementalSource(buf); ``` ## ImageSource @@ -1357,7 +1363,7 @@ getImageInfo(index: number, callback: AsyncCallback\): void **示例:** ```js -imageSourceApi.getImageInfo(0,(error, imageInfo) => { +imageSourceApi.getImageInfo(0,(error, imageInfo : image.ImageInfo) => { if(error) { console.log('getImageInfo failed.'); } else { @@ -1383,7 +1389,7 @@ getImageInfo(callback: AsyncCallback\): void **示例:** ```js -imageSourceApi.getImageInfo(imageInfo => { +imageSourceApi.getImageInfo((imageInfo : image.ImageInfo) => { console.log('Succeeded in obtaining the image information.'); }) ``` @@ -1411,10 +1417,11 @@ getImageInfo(index?: number): Promise\ **示例:** ```js +import {BusinessError} from '@ohos.base' imageSourceApi.getImageInfo(0) - .then(imageInfo => { + .then((imageInfo : image.ImageInfo) => { console.log('Succeeded in obtaining the image information.'); - }).catch(error => { + }).catch((error : BusinessError) => { console.log('Failed to obtain the image information.'); }) ``` @@ -1444,7 +1451,7 @@ getImageProperty(key:string, options?: GetImagePropertyOptions): Promise\ { + .then((data : string) => { console.log('Succeeded in getting the value of the specified attribute key of the image.'); }) ``` @@ -1467,7 +1474,7 @@ getImageProperty(key:string, callback: AsyncCallback\): void **示例:** ```js -imageSourceApi.getImageProperty("BitsPerSample",(error,data) => { +imageSourceApi.getImageProperty("BitsPerSample",(error, data : string) => { if(error) { console.log('Failed to get the value of the specified attribute key of the image.'); } else { @@ -1495,8 +1502,8 @@ getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCa **示例:** ```js -let property = { index: 0, defaultValue: '9999' } -imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => { +let property : image.GetImagePropertyOptions = { index: 0, defaultValue: '9999' } +imageSourceApi.getImageProperty("BitsPerSample",property,(error, data : string) => { if(error) { console.log('Failed to get the value of the specified attribute key of the image.'); } else { @@ -1530,7 +1537,7 @@ modifyImageProperty(key: string, value: string): Promise\ ```js imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => { - const w = imageSourceApi.getImageProperty("ImageWidth") + const w : string = imageSourceApi.getImageProperty("ImageWidth"); console.info('w', w); }) ``` @@ -1583,7 +1590,7 @@ updateData(buf: ArrayBuffer, isFinished: boolean, value: number, length: number) **示例:** ```js -const array = new ArrayBuffer(100); +const array : ArrayBuffer = new ArrayBuffer(100); imageSourceApi.updateData(array, false, 0, 10).then(data => { console.info('Succeeded in updating data.'); }) @@ -1611,7 +1618,7 @@ updateData(buf: ArrayBuffer, isFinished: boolean, value: number, length: number, **示例:** ```js -const array = new ArrayBuffer(100); +const array : ArrayBuffer = new ArrayBuffer(100); imageSourceApi.updateData(array, false, 0, 10,(error,data )=> { if(data !== undefined){ console.info('Succeeded in updating data.'); @@ -1642,9 +1649,10 @@ createPixelMap(options?: DecodingOptions): Promise\ **示例:** ```js -imageSourceApi.createPixelMap().then(pixelmap => { +import {BusinessError} from '@ohos.base' +imageSourceApi.createPixelMap().then((pixelmap : image.PixelMap) => { console.log('Succeeded in creating pixelmap object through image decoding parameters.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('Failed to create pixelmap object through image decoding parameters.'); }) ``` @@ -1666,7 +1674,7 @@ createPixelMap(callback: AsyncCallback\): void **示例:** ```js -imageSourceApi.createPixelMap((err, pixelmap) => { +imageSourceApi.createPixelMap((err, pixelmap : image.PixelMap) => { console.info('Succeeded in creating pixelmap object.'); }) ``` @@ -1689,7 +1697,7 @@ createPixelMap(options: DecodingOptions, callback: AsyncCallback\): vo **示例:** ```js -let decodingOptions = { +let decodingOptions : image.DecodingOptions = { sampleSize: 1, editable: true, desiredSize: { width: 1, height: 2 }, @@ -1698,7 +1706,7 @@ let decodingOptions = { desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 }, index: 0 }; -imageSourceApi.createPixelMap(decodingOptions, pixelmap => { +imageSourceApi.createPixelMap(decodingOptions, pixelmap : image.PixelMap => { console.log('Succeeded in creating pixelmap object.'); }) ``` @@ -1738,7 +1746,7 @@ createPixelMapList(options?: DecodingOptions): Promise>; **示例:** ```js -let decodeOpts = { +let decodeOpts : image.DecodingOptions = { sampleSize: 1, editable: true, desiredSize: { width: 198, height: 202 }, @@ -1746,7 +1754,7 @@ let decodeOpts = { desiredPixelFormat: 3, index: 0, }; -let pixelmaplist = imageSourceApi.createPixelMapList(decodeOpts); +let pixelmaplist : Array = imageSourceApi.createPixelMapList(decodeOpts); ``` ### createPixelMapList10+ @@ -1778,7 +1786,7 @@ createPixelMapList(callback: AsyncCallback>): void **示例:** ```js -imageSourceApi.createPixelMapList( pixelmaplist => { +imageSourceApi.createPixelMapList( (pixelmaplist : Array) => { console.info('Succeeded in creating pixelmaplist object.'); }) ``` @@ -1813,7 +1821,7 @@ createPixelMapList(options: DecodingOptions, callback: AsyncCallback { +imageSourceApi.createPixelMapList(decodeOpts, (pixelmaplist : Array) => { console.log('Succeeded in creating pixelmaplist object.'); }) ``` @@ -1857,7 +1865,7 @@ getDelayTimeList(callback: AsyncCallback>): void; **示例:** ```js -imageSourceApi.getDelayTimeList( delayTimes => { +imageSourceApi.getDelayTimeList( (delayTimes : Array) => { console.log('Succeeded in getting delay time.'); }); ``` @@ -1893,7 +1901,7 @@ getDelayTimeList(): Promise>; **示例:** ```js -let delayTimes = imageSourceApi.getDelayTimeList(); +let delayTimes : Array = imageSourceApi.getDelayTimeList(); ``` ### getFrameCount10+ @@ -1927,7 +1935,7 @@ getFrameCount(callback: AsyncCallback\): void; **示例:** ```js -imageSourceApi.getFrameCount( frameCount => { +imageSourceApi.getFrameCount( (frameCount : number) => { console.log('Succeeded in getting frame count.'); }); ``` @@ -1963,7 +1971,7 @@ getFrameCount(): Promise\; **示例:** ```js -let frameCount = imageSourceApi.getFrameCount(); +let frameCount : number = imageSourceApi.getFrameCount(); ``` ### release @@ -2005,9 +2013,10 @@ release(): Promise\ **示例:** ```js +import {BusinessError} from '@ohos.base' imageSourceApi.release().then(()=>{ console.log('Succeeded in releasing the image source instance.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('Failed to release the image source instance.'); }) ``` @@ -2029,7 +2038,7 @@ createImagePacker(): ImagePacker **示例:** ```js -const imagePackerApi = image.createImagePacker(); +const imagePackerApi : image.ImagePacker = image.createImagePacker(); ``` ## ImagePacker @@ -2063,9 +2072,9 @@ packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\ {}) +const imageSourceApi : image.ImageSource = image.createImageSource(0); +let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 }; +imagePackerApi.packing(imageSourceApi, packOpts, data : ArrayBuffer => {}) ``` ### packing @@ -2092,12 +2101,13 @@ packing(source: ImageSource, option: PackingOption): Promise\ **示例:** ```js -const imageSourceApi = image.createImageSource(0); -let packOpts = { format:"image/jpeg", quality:98 } +import {BusinessError} from '@ohos.base' +const imageSourceApi : image.ImageSource = image.createImageSource(0); +let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 } imagePackerApi.packing(imageSourceApi, packOpts) - .then( data => { + .then( data : ArrayBuffer => { console.log('packing succeeded.'); - }).catch(error => { + }).catch((error : BusinessError) => { console.log('packing failed.'); }) ``` @@ -2121,12 +2131,12 @@ packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\ { - let packOpts = { format:"image/jpeg", quality:98 } - imagePackerApi.packing(pixelmap, packOpts, data => { +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap : image.image.PixelMap) => { + let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts, data : ArrayBuffer => { console.log('Succeeded in packing the image.'); }) }) @@ -2156,15 +2166,16 @@ packing(source: PixelMap, option: PackingOption): Promise\ **示例:** ```js -const color = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts).then((pixelmap) => { - let packOpts = { format:"image/jpeg", quality:98 } +import {BusinessError} from '@ohos.base' +const color : ArrayBuffer = new ArrayBuffer(96); //96为需要创建的像素buffer大小,取值为:height * width *4 +let bufferArr : Uint8Array = new Uint8Array(color); +let opts : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap : image.PixelMap) => { + let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 } imagePackerApi.packing(pixelmap, packOpts) - .then( data => { + .then( data : ArrayBuffer => { console.log('Succeeded in packing the image.'); - }).catch(error => { + }).catch((error : BusinessError) => { console.log('Failed to pack the image..'); }) }) @@ -2209,9 +2220,10 @@ release(): Promise\ **示例:** ```js +import {BusinessError} from '@ohos.base' imagePackerApi.release().then(()=>{ console.log('Succeeded in releasing image packaging.'); -}).catch((error)=>{ +}).catch((error : BusinessError)=>{ console.log('Failed to release image packaging.'); }) ``` @@ -2242,7 +2254,7 @@ createImageReceiver(width: number, height: number, format: number, capacity: num **示例:** ```js -var receiver = image.createImageReceiver(8192, 8, 2000, 8); +var receiver image.ImageReceiver = image.createImageReceiver(8192, 8, 2000, 8); ``` ## ImageReceiver9+ @@ -2278,7 +2290,7 @@ getReceivingSurfaceId(callback: AsyncCallback\): void **示例:** ```js -receiver.getReceivingSurfaceId((err, id) => { +receiver.getReceivingSurfaceId((err, id : string) => { if(err) { console.log('getReceivingSurfaceId failed.'); } else { @@ -2304,9 +2316,10 @@ getReceivingSurfaceId(): Promise\ **示例:** ```js -receiver.getReceivingSurfaceId().then( id => { +import {BusinessError} from '@ohos.base' +receiver.getReceivingSurfaceId().then( (id : string) => { console.log('getReceivingSurfaceId succeeded.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('getReceivingSurfaceId failed.'); }) ``` @@ -2328,7 +2341,7 @@ readLatestImage(callback: AsyncCallback\): void **示例:** ```js -receiver.readLatestImage((err, img) => { +receiver.readLatestImage((err, img : image.Image) => { if(err) { console.log('readLatestImage failed.'); } else { @@ -2354,9 +2367,10 @@ readLatestImage(): Promise\ **示例:** ```js -receiver.readLatestImage().then(img => { +import {BusinessError} from '@ohos.base' +receiver.readLatestImage().then((img : image.Image) => { console.log('readLatestImage succeeded.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('readLatestImage failed.'); }) ``` @@ -2378,7 +2392,7 @@ readNextImage(callback: AsyncCallback\): void **示例:** ```js -receiver.readNextImage((err, img) => { +receiver.readNextImage((err, img : image.Image) => { if(err) { console.log('readNextImage failed.'); } else { @@ -2404,9 +2418,10 @@ readNextImage(): Promise\ **示例:** ```js -receiver.readNextImage().then(img => { +import {BusinessError} from '@ohos.base' +receiver.readNextImage().then((img : image.Image) => { console.log('readNextImage succeeded.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('readNextImage failed.'); }) ``` @@ -2469,9 +2484,10 @@ release(): Promise\ **示例:** ```js +import {BusinessError} from '@ohos.base' receiver.release().then(() => { console.log('release succeeded.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('release failed.'); }) ``` @@ -2502,7 +2518,7 @@ createImageCreator(width: number, height: number, format: number, capacity: numb **示例:** ```js -var creator = image.createImageCreator(8192, 8, 4, 8); +var creator : image.ImageCreator = image.createImageCreator(8192, 8, 4, 8); ``` ## ImageCreator9+ @@ -2536,7 +2552,7 @@ dequeueImage(callback: AsyncCallback\): void **示例:** ```js -creator.dequeueImage((err, img) => { +creator.dequeueImage((err, img : image.Image) => { if (err) { console.info('dequeueImage failed.'); } @@ -2561,9 +2577,10 @@ dequeueImage(): Promise\ **示例:** ```js -creator.dequeueImage().then(img => { +import {BusinessError} from '@ohos.base' +creator.dequeueImage().then((img : image.Image) => { console.info('dequeueImage succeeded.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('dequeueImage failed: ' + error); }) ``` @@ -2586,10 +2603,10 @@ queueImage(interface: Image, callback: AsyncCallback\): void **示例:** ```js -creator.dequeueImage().then(img => { +creator.dequeueImage().then((img : image.Image) => { //绘制图片 - img.getComponent(4).then(component => { - var bufferArr = new Uint8Array(component.byteBuffer); + img.getComponent(4).then(component : image.Component => { + var bufferArr : Uint8Array = new Uint8Array(component.byteBuffer); for (var i = 0; i < bufferArr.length; i += 4) { bufferArr[i] = 0; //B bufferArr[i + 1] = 0; //G @@ -2630,10 +2647,11 @@ queueImage(interface: Image): Promise\ **示例:** ```js -creator.dequeueImage().then(img => { +import {BusinessError} from '@ohos.base' +creator.dequeueImage().then((img : image.Image) => { //绘制图片 - img.getComponent(4).then(component => { - var bufferArr = new Uint8Array(component.byteBuffer); + img.getComponent(4).then(component : image.Component => { + var bufferArr : Uint8Array = new Uint8Array(component.byteBuffer); for (var i = 0; i < bufferArr.length; i += 4) { bufferArr[i] = 0; //B bufferArr[i + 1] = 0; //G @@ -2643,7 +2661,7 @@ creator.dequeueImage().then(img => { }) creator.queueImage(img).then(() => { console.info('queueImage succeeded.'); - }).catch(error => { + }).catch((error : BusinessError) => { console.info('queueImage failed: ' + error); }) }) @@ -2717,9 +2735,10 @@ release(): Promise\ **示例:** ```js +import {BusinessError} from '@ohos.base' creator.release().then(() => { console.info('release succeeded'); -}).catch(error => { +}).catch((error : BusinessError) => { console.info('release failed'); }) ``` @@ -2756,7 +2775,7 @@ getComponent(componentType: ComponentType, callback: AsyncCallback\): **示例:** ```js -img.getComponent(4, (err, component) => { +img.getComponent(4, (err, component : image.Component) => { if(err) { console.log('getComponent failed.'); } else { @@ -2788,7 +2807,7 @@ getComponent(componentType: ComponentType): Promise\ **示例:** ```js -img.getComponent(4).then(component => { }) +img.getComponent(4).then((component : image.Component) => { }) ``` ### release9+ @@ -2834,9 +2853,10 @@ release(): Promise\ **示例:** ```js +import {BusinessError} from '@ohos.base' img.release().then(() =>{ console.log('release succeeded.'); -}).catch(error => { +}).catch((error : BusinessError) => { console.log('release failed.'); }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md index 70808c6cf9a511ae825b4ab8b878978cd4b094b8..39cc0ef3d056849e252150c33b6955d7682ed2e2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @@ -17,14 +17,16 @@ WindowExtensionContext模块提供[WindowExtensionAbility](js-apis-application-w 在使用WindowExtensionContext的功能前,需要通过WindowExtensionAbility子类实例获取。 ```ts - import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; +import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; +import WindowExtensionContext from 'application/WindowExtensionContext'; - let context; - class WindowExtAbility extends WindowExtensionAbility { - onConnect() { - context = this.context; // 获取WindowExtensionContext - } +let context: WindowExtensionContext | null = null; + +class WindowExtAbility extends WindowExtensionAbility { + onConnect() { + context = this.context; // 获取WindowExtensionContext } +} ``` ## WindowExtensionContext.startAbility @@ -46,28 +48,36 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& **示例:** ```ts - var want = { - bundleName: 'com.example.myapplication', - abilityName: 'MainAbility' - }; - var options = { - windowMode: 102 - }; - - try { - this.context.startAbility(want, options, (error) => { - if (error.code) { - // 处理业务逻辑错误 - console.error('startAbility failed, error.code: ${error.code}, error.message: ${error.message}'); - return; - } - // 执行正常业务 - console.log('startAbility succeed'); - }); - } catch (paramError) { - // 处理入参错误异常 - console.error('error.code: ${paramError.code}, error.message: ${paramError.message}'); - } +import { BusinessError } from '@ohos.base'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; + +let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'MainAbility' +}; +let options: StartOptions = { + windowMode: 102 +}; + +try { + this.context.startAbility(want, options, (error: BusinessError) => { + let message = (error as BusinessError).message; + let errCode = (error as BusinessError).code; + if (errCode) { + // 处理业务逻辑错误 + console.error('startAbility failed, error.code: ${errCode}, error.message: ${message}'); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); +} catch (paramError) { + // 处理入参错误异常 + let message = (paramError as BusinessError).message; + let errCode = (paramError as BusinessError).code; + console.error('error.code: ${errCode}, error.message: ${message}'); +} ``` ## WindowExtensionContext.startAbility @@ -94,26 +104,34 @@ startAbility(want: Want, options?: StartOptions): Promise\ **示例:** ```ts - var want = { - bundleName: 'com.example.myapp', - abilityName: 'MainAbility' - }; - var options = { - windowMode: 102, - }; - - try { - this.context.startAbility(want, options) - .then((data) => { - // 执行正常业务 - console.log('startAbility succeed'); - }) - .catch((error) => { - // 处理业务逻辑错误 - console.error('startAbility failed, error.code: ${error.code}, error.message: ${error.message}'); - }); - } catch (paramError) { - // 处理入参错误异常 - console.error('error.code: ${paramError.code}, error.message: ${paramError.message}'); - } +import { BusinessError } from '@ohos.base'; +import Want from '@ohos.app.ability.Want'; +import StartOptions from '@ohos.app.ability.StartOptions'; + +let want: Want = { + bundleName: 'com.example.myapp', + abilityName: 'MainAbility' +}; +let options: StartOptions = { + windowMode: 102, +}; + +try { + this.context.startAbility(want, options) + .then(() => { + // 执行正常业务 + console.log('startAbility succeed'); + }) + .catch((error: BusinessError) => { + // 处理业务逻辑错误 + let message = (error as BusinessError).message; + let errCode = (error as BusinessError).code; + console.error('startAbility failed, error.code: ${errCode}, error.message: ${message}'); + }); +} catch (paramError) { + // 处理入参错误异常 + let message = (paramError as BusinessError).message; + let errCode = (paramError as BusinessError).code; + console.error('error.code: ${errCode}, error.message: ${message}'); +} ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index 7ec39051e1b93cbfc8d9be6e04bc4db277bf913f..c259c9689918ecbe0ce31d5d34792e2560c69ee9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -7,7 +7,7 @@ ## 导入模块 -```js +```ts import mediaLibrary from '@ohos.multimedia.mediaLibrary'; ``` @@ -37,21 +37,12 @@ getMediaLibrary(context: Context): MediaLibrary | ----------------------------- | :---- | | [MediaLibrary](#medialibrary) | 媒体库实例。 | -**示例:(从API version 9开始)** +**示例:** ```ts // 获取mediaLibrary实例,后续用到此实例均采用此处获取的实例。 const context = getContext(this); -let media = mediaLibrary.getMediaLibrary(context); -``` - -**示例:(API version 8)** - -```js -import featureAbility from '@ohos.ability.featureAbility'; - -let context = featureAbility.getContext(); -let media = mediaLibrary.getMediaLibrary(context); +let media: mediaLibrary.MediaLibrary = mediaLibrary.getMediaLibrary(context); ``` ## mediaLibrary.getMediaLibrary @@ -76,8 +67,8 @@ getMediaLibrary(): MediaLibrary **示例:** -```js -let media = mediaLibrary.getMediaLibrary(); +```ts +let media: mediaLibrary.MediaLibrary = mediaLibrary.getMediaLibrary(); ``` ## MediaLibrary @@ -106,12 +97,12 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileRe **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; // 创建文件获取选项,此处参数为获取image类型的文件资源。 - let imagesFetchOp = { + let imagesFetchOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; @@ -184,12 +175,14 @@ getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; // 创建文件获取选项,此处参数为获取image类型的文件资源。 - let imagesFetchOp = { + let imagesFetchOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; @@ -218,11 +211,11 @@ async function example() { } // 释放FetchFileResult实例并使其失效。无法调用其他方法。 fetchFileResult.close(); - }).catch((error) => { + }).catch((error: BusinessError) => { // 调用getFirstObject接口失败。 console.error('get first object failed with error: ' + error); }); - }).catch((error) => { + }).catch((error: BusinessError) => { // 调用getFileAssets接口失败。 console.error('get file assets failed with error: ' + error); }); @@ -250,7 +243,7 @@ on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange' **示例:** -```js +```ts media.on('imageChange', () => { // image file had changed, do something. }); @@ -277,7 +270,7 @@ off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange **示例:** -```js +```ts media.off('imageChange', () => { // stop listening successfully. }); @@ -309,7 +302,7 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string, cal **示例:** -```js +```ts async function example() { // 使用Callback方式创建Image类型文件。 let mediaType = mediaLibrary.MediaType.IMAGE; @@ -356,7 +349,9 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string): Pr **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { // 使用Promise方式创建Image类型文件。 let mediaType = mediaLibrary.MediaType.IMAGE; @@ -364,7 +359,7 @@ async function example() { const path = await media.getPublicDirectory(DIR_IMAGE); media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => { console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset)); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('createAsset failed with error: ' + error); }); } @@ -402,11 +397,13 @@ deleteAsset(uri: string): Promise\ **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let fileType = mediaLibrary.MediaType.FILE; - let option = { + let option: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; @@ -418,7 +415,7 @@ async function example() { } media.deleteAsset(asset.uri).then(() => { console.info('deleteAsset successfully'); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('deleteAsset failed with error: ' + error); }); fetchFileResult.close(); @@ -452,11 +449,11 @@ deleteAsset(uri: string, callback: AsyncCallback\): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let fileType = mediaLibrary.MediaType.FILE; - let option = { + let option: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; @@ -498,7 +495,7 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): **示例:** -```js +```ts let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; media.getPublicDirectory(DIR_CAMERA, (error, dicResult) => { if (dicResult == 'Camera/') { @@ -535,7 +532,9 @@ getPublicDirectory(type: DirectoryType): Promise<string> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; media.getPublicDirectory(DIR_CAMERA).then((dicResult) => { @@ -544,7 +543,7 @@ async function example() { } else { console.error('getPublicDirectory DIR_CAMERA failed'); } - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('getPublicDirectory failed with error: ' + error); }); } @@ -574,13 +573,13 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array<Album& **示例:** -```js +```ts async function example() { - let AlbumNoArgsfetchOp = { + let albumFetchOp: mediaLibrary.MediaFetchOptions = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', selectionArgs: ['Camera'], }; - media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { + media.getAlbums(albumFetchOp, (error, albumList) => { if (albumList != undefined) { console.info('getAlbums successfully: ' + JSON.stringify(albumList)); } else { @@ -619,15 +618,17 @@ getAlbums(options: MediaFetchOptions): Promise<Array<Album>> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { - let AlbumNoArgsfetchOp = { + let albumFetchOp: mediaLibrary.MediaFetchOptions = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', selectionArgs: ['Camera'], }; - media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { + media.getAlbums(albumFetchOp).then((albumList) => { console.info('getAlbums successfully: ' + JSON.stringify(albumList)); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('getAlbums failed with error: ' + error); }); } @@ -654,7 +655,7 @@ release(callback: AsyncCallback<void>): void **示例:** -```js +```ts media.release(() => { // do something. }); @@ -681,7 +682,7 @@ release(): Promise<void> **示例:** -```js +```ts media.release(); ``` @@ -707,8 +708,8 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>) **示例:** -```js -let option = { +```ts +let option: mediaLibrary.MediaAssetOption = { src : '/data/storage/el2/base/haps/entry/image.png', mimeType : 'image/*', relativePath : 'Pictures/' @@ -750,8 +751,10 @@ storeMediaAsset(option: MediaAssetOption): Promise<string> **示例:** -```js -let option = { +```ts +import { BusinessError } from '@ohos.base'; + +let option: mediaLibrary.MediaAssetOption = { src : '/data/storage/el2/base/haps/entry/image.png', mimeType : 'image/*', relativePath : 'Pictures/' @@ -759,7 +762,7 @@ let option = { mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { console.info('Media resources stored.'); // Obtain the URI that stores media resources. -}).catch((error) => { +}).catch((error: BusinessError) => { console.error('storeMediaAsset failed with error: ' + error); }); ``` @@ -787,7 +790,7 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal **示例:** -```js +```ts let images = [ 'file://media/xxxx/2', 'file://media/xxxx/3' @@ -830,7 +833,7 @@ startImagePreview(images: Array<string>, callback: AsyncCallback<void&g **示例:** -```js +```ts let images = [ 'file://media/xxxx/2', 'file://media/xxxx/3' @@ -878,7 +881,9 @@ startImagePreview(images: Array<string>, index?: number): Promise<void& **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + let images = [ 'file://media/xxxx/2', 'file://media/xxxx/3' @@ -892,7 +897,7 @@ let images = [ let index = 1; mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { console.info('Succeeded in previewing the images.'); -}).catch((error) => { +}).catch((error: BusinessError) => { console.error('startImagePreview failed with error: ' + error); }); ``` @@ -919,7 +924,7 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array< **示例:** -```js +```ts let option : mediaLibrary.MediaSelectOption = { type : 'media', count : 2 @@ -961,7 +966,9 @@ startMediaSelect(option: MediaSelectOption): Promise<Array<string>> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + let option : mediaLibrary.MediaSelectOption = { type : 'media', count : 2 @@ -969,7 +976,7 @@ let option : mediaLibrary.MediaSelectOption = { mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { console.info('Media resources selected.'); // Obtain the media selection value. -}).catch((error) => { +}).catch((error: BusinessError) => { console.error('startMediaSelect failed with error: ' + error); }); ``` @@ -998,7 +1005,9 @@ getActivePeers(): Promise\>; **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { media.getActivePeers().then((devicesInfo) => { if (devicesInfo != undefined) { @@ -1006,7 +1015,7 @@ async function example() { } else { console.info('get distributed info is undefined!'); } - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('get distributed info failed with error: ' + error); }); } @@ -1036,7 +1045,7 @@ getActivePeers(callback: AsyncCallback\>): void; **示例:** -```js +```ts async function example() { media.getActivePeers((error, devicesInfo) => { if (devicesInfo != undefined) { @@ -1072,7 +1081,9 @@ getAllPeers(): Promise\>; **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { media.getAllPeers().then((devicesInfo) => { if (devicesInfo != undefined) { @@ -1080,7 +1091,7 @@ async function example() { } else { console.info('get distributed info is undefined!'); } - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('get distributed info failed with error: ' + error); }); } @@ -1110,7 +1121,7 @@ getAllPeers(callback: AsyncCallback\>): void; **示例:** -```js +```ts async function example() { media.getAllPeers((error, devicesInfo) => { if (devicesInfo != undefined) { @@ -1182,11 +1193,11 @@ isDirectory(callback: AsyncCallback<boolean>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1226,11 +1237,13 @@ isDirectory():Promise<boolean> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1239,7 +1252,7 @@ async function example() { const asset = await fetchFileResult.getFirstObject(); asset.isDirectory().then((isDirectory) => { console.info('isDirectory result:' + isDirectory); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('isDirectory failed with error: ' + error); }); fetchFileResult.close(); @@ -1269,11 +1282,11 @@ commitModify(callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1311,11 +1324,11 @@ commitModify(): Promise<void> **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1353,7 +1366,7 @@ open(mode: string, callback: AsyncCallback<number>): void **示例:** -```js +```ts async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; @@ -1399,7 +1412,9 @@ open(mode: string): Promise<number> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; @@ -1407,7 +1422,7 @@ async function example() { const asset = await media.createAsset(mediaType, 'image00003.jpg', path); asset.open('rw').then((fd) => { console.info('File open fd: ' + fd); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('File open failed with error: ' + error); }); } @@ -1436,11 +1451,13 @@ close(fd: number, callback: AsyncCallback<void>): void **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1456,7 +1473,7 @@ async function example() { console.info('asset.close successfully'); } }); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('File open failed with error: ' + error); }); fetchFileResult.close(); @@ -1491,11 +1508,13 @@ close(fd: number): Promise<void> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1509,7 +1528,7 @@ async function example() { }).catch((closeErr) => { console.error('asset.close fail, closeErr: ' + closeErr); }); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('open File failed with error: ' + error); }); fetchFileResult.close(); @@ -1538,11 +1557,11 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1583,16 +1602,16 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', }; - let size = { width: 720, height: 720 }; + let size: mediaLibrary.Size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size, (error, pixelmap) => { @@ -1634,21 +1653,23 @@ getThumbnail(size?: Size): Promise<image.PixelMap> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', }; - let size = { width: 720, height: 720 }; + let size: mediaLibrary.Size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size).then((pixelmap) => { console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap)); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('mediaLibrary getThumbnail failed with error: ' + error); }); fetchFileResult.close(); @@ -1678,11 +1699,11 @@ favorite(isFavorite: boolean, callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1728,11 +1749,13 @@ favorite(isFavorite: boolean): Promise<void> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1741,7 +1764,7 @@ async function example() { const asset = await fetchFileResult.getFirstObject(); asset.favorite(true).then(() => { console.info('mediaLibrary favorite Successful'); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('mediaLibrary favorite failed with error: ' + error); }); fetchFileResult.close(); @@ -1770,11 +1793,11 @@ isFavorite(callback: AsyncCallback<boolean>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1814,11 +1837,13 @@ isFavorite():Promise<boolean> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1827,7 +1852,7 @@ async function example() { const asset = await fetchFileResult.getFirstObject(); asset.isFavorite().then((isFavorite) => { console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('mediaLibrary favoriisFavoritete failed with error: ' + error); }); fetchFileResult.close(); @@ -1859,11 +1884,11 @@ trash(isTrash: boolean, callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1911,11 +1936,13 @@ trash(isTrash: boolean): Promise<void> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1924,7 +1951,7 @@ async function example() { const asset = await fetchFileResult.getFirstObject(); asset.trash(true).then(() => { console.info('trash successfully'); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('trash failed with error: ' + error); }); fetchFileResult.close(); @@ -1953,11 +1980,11 @@ isTrash(callback: AsyncCallback<boolean>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -1997,11 +2024,13 @@ isTrash():Promise<boolean> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2010,7 +2039,7 @@ async function example() { const asset = await fetchFileResult.getFirstObject(); asset.isTrash().then((isTrash) => { console.info('isTrash result: ' + isTrash); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('isTrash failed with error: ' + error); }); fetchFileResult.close(); @@ -2045,11 +2074,11 @@ getCount(): number **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let fileType = mediaLibrary.MediaType.FILE; - let getFileCountOneOp = { + let getFileCountOneOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2081,11 +2110,11 @@ isAfterLast(): boolean **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2094,10 +2123,10 @@ async function example() { const fetchCount = fetchFileResult.getCount(); console.info('mediaLibrary fetchFileResult.getCount, count:' + fetchCount); let fileAsset = await fetchFileResult.getFirstObject(); - for (var i = 1; i < fetchCount; i++) { + for (let i = 1; i < fetchCount; i++) { fileAsset = await fetchFileResult.getNextObject(); if(i == fetchCount - 1) { - var result = fetchFileResult.isAfterLast(); + let result = fetchFileResult.isAfterLast(); console.info('mediaLibrary fileAsset isAfterLast result: ' + result); fetchFileResult.close(); } @@ -2119,11 +2148,11 @@ close(): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2153,11 +2182,11 @@ getFirstObject(callback: AsyncCallback<FileAsset>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2194,11 +2223,13 @@ getFirstObject(): Promise<FileAsset> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2207,7 +2238,7 @@ async function example() { fetchFileResult.getFirstObject().then((fileAsset) => { console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName); fetchFileResult.close(); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('getFirstObject failed with error: ' + error); }); } @@ -2234,11 +2265,11 @@ getNextObject(callback: AsyncCallback<FileAsset>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2281,11 +2312,13 @@ getNextObject(): Promise<FileAsset> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2297,7 +2330,7 @@ async function example() { fetchFileResult.getNextObject().then((fileAsset) => { console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); fetchFileResult.close(); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('fetchFileResult getNextObject failed with error: ' + error); }) } @@ -2324,11 +2357,11 @@ getLastObject(callback: AsyncCallback<FileAsset>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2365,11 +2398,13 @@ getLastObject(): Promise<FileAsset> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2378,7 +2413,7 @@ async function example() { fetchFileResult.getLastObject().then((fileAsset) => { console.info('getLastObject successfully, displayName: ' + fileAsset.displayName); fetchFileResult.close(); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('getLastObject failed with error: ' + error); }); } @@ -2405,11 +2440,11 @@ getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2452,11 +2487,13 @@ getPositionObject(index: number): Promise<FileAsset> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2465,7 +2502,7 @@ async function example() { fetchFileResult.getPositionObject(0).then((fileAsset) => { console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName); fetchFileResult.close(); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('getPositionObject failed with error: ' + error); }); } @@ -2491,11 +2528,11 @@ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void **示例:** -```js +```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2534,11 +2571,13 @@ getAllObject(): Promise<Array<FileAsset>> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { + let getImageOp: mediaLibrary.MediaFetchOptions = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + ' DESC', @@ -2549,7 +2588,7 @@ async function example() { console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName); } fetchFileResult.close(); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('getAllObject failed with error: ' + error); }); } @@ -2599,14 +2638,14 @@ commitModify(callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { // 获取相册需要先预置相册和资源,示例代码为预置的新建相册1。 - let AlbumNoArgsfetchOp = { + let albumFetchOp: mediaLibrary.MediaFetchOptions = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', selectionArgs: ['新建相册1'], }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const albumList = await media.getAlbums(albumFetchOp); const album = albumList[0]; album.albumName = 'hello'; album.commitModify((error) => { @@ -2641,19 +2680,21 @@ commitModify(): Promise<void> **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { // 获取相册需要先预置相册和资源,示例代码为预置的新建相册1。 - let AlbumNoArgsfetchOp = { + let albumFetchOp: mediaLibrary.MediaFetchOptions = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', selectionArgs: ['新建相册1'], }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const albumList = await media.getAlbums(albumFetchOp); const album = albumList[0]; album.albumName = 'hello'; album.commitModify().then(() => { console.info('commitModify successfully'); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('commitModify failed with error: ' + error); }); } @@ -2681,15 +2722,15 @@ getFileAssets(callback: AsyncCallback<FetchFileResult>): void **示例:** -```js +```ts async function example() { // 获取相册需要先预置相册和资源,示例代码为预置的新建相册1。 - let AlbumNoArgsfetchOp = { + let albumFetchOp: mediaLibrary.MediaFetchOptions = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', selectionArgs: ['新建相册1'], }; // 获取符合检索要求的相册,返回相册列表。 - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const albumList = await media.getAlbums(albumFetchOp); const album = albumList[0]; // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源。 album.getFileAssets((error, fetchFileResult) => { @@ -2727,19 +2768,19 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileRe **示例:** -```js +```ts async function example() { // 获取相册需要先预置相册和资源,示例代码为预置的新建相册1。 - let AlbumNoArgsfetchOp = { + let albumFetchOp: mediaLibrary.MediaFetchOptions = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', selectionArgs: ['新建相册1'], }; - let fileNoArgsfetchOp = { + let fileNoArgsfetchOp: mediaLibrary.MediaFetchOptions = { selections: '', selectionArgs: [], }; // 获取符合检索要求的相册,返回相册列表。 - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const albumList = await media.getAlbums(albumFetchOp); const album = albumList[0]; // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源。 album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { @@ -2782,26 +2823,28 @@ async function example() { **示例:** -```js +```ts +import { BusinessError } from '@ohos.base'; + async function example() { // 获取相册需要先预置相册和资源,示例代码为预置的新建相册1。 - let AlbumNoArgsfetchOp = { + let albumFetchOp: mediaLibrary.MediaFetchOptions = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', selectionArgs: ['新建相册1'], }; - let fileNoArgsfetchOp = { + let fileNoArgsfetchOp: mediaLibrary.MediaFetchOptions = { selections: '', selectionArgs: [], }; // 获取符合检索要求的相册,返回相册列表。 - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const albumList = await media.getAlbums(albumFetchOp); const album = albumList[0]; // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源。 album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { let count = fetchFileResult.getCount(); console.info('album getFileAssets successfully, count: ' + count); fetchFileResult.close(); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('album getFileAssets failed with error: ' + error); }); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md index 2bd615b3b05fdacd3480616e8d6df699031181ad..51bfc53a6a7df13306bf66150c9a579c74ec24bd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md @@ -1969,8 +1969,8 @@ connection.getDefaultNet().then(function (netHandle) { | 名称 | 类型 | 必填 | 说明 | | --------------------- | ---------------------------------- | --- | ------------------------ | -| linkUpBandwidthKbps | number | 否 | 上行(设备到网络)带宽。 | -| linkDownBandwidthKbps | number | 否 | 下行(网络到设备)带宽。 | +| linkUpBandwidthKbps | number | 否 | 上行(设备到网络)带宽,0表示无法评估当前网络带宽。 | +| linkDownBandwidthKbps | number | 否 | 下行(网络到设备)带宽,0表示无法评估当前网络带宽。 | | networkCap | Array\<[NetCap](#netcap)> | 否 | 网络具体能力。 | | bearerTypes | Array\<[NetBearType](#netbeartype)> | 是 | 网络类型。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index 9c1aba77af5a84e03d72b7a13ec1b75cada03a37..6a5128dff9f58989d915cf010524e88f52ca4c98 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -90,7 +90,9 @@ activateOsAccount(localId: number, callback: AsyncCallback<void>): void } }); } catch (err) { - console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code + let message = (err as BusinessError).message + console.error(`activateOsAccount failed, code is ${code}, message is ${message}`); } ``` @@ -178,7 +180,9 @@ checkMultiOsAccountEnabled(callback: AsyncCallback<boolean>): void } }); } catch (err) { - console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code + let message = (err as BusinessError).message + console.error(`checkMultiOsAccountEnabled failed, code is ${code}, message is ${message}`); } ``` @@ -214,7 +218,9 @@ checkMultiOsAccountEnabled(): Promise<boolean> console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); }); } catch (err) { - console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); + let code = (err as BusinessError).code + let message = (err as BusinessError).message + console.error(`checkMultiOsAccountEnabled failed, code is ${code}, message is ${message}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md index 897968a41180dfcab492a5d67ece9174b223e727..3c8cded98bb01d299e1c53aaa699cce0dcc5d81a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @@ -219,10 +219,8 @@ import { BusinessError } from '@ohos.base'; | 名称 | 值 | 说明 | | -------------------- | ---- | ---- | -| DEVICE_TYPE_PHONE | 0x00 | 手机 | | DEVICE_TYPE_TABLET | 0x01 | 平板 | | DEVICE_TYPE_CAR | 0x02 | 汽车 | -| DEVICE_TYPE_PC | 0x03 | 电脑 | | DEVICE_TYPE_TV | 0x04 | 电视 | | DEVICE_TYPE_WEARABLE | 0x06 | 穿戴 | @@ -3950,7 +3948,7 @@ getDeviceCapability(): Promise<DeviceCapability> release() -用户释放创建的resourceManager。 +用户释放创建的resourceManager, 此接口暂不支持。 **系统能力**:SystemCapability.Global.ResourceManager diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index 8232aa366630f12ff418d461f01b8ed3c58b428d..9fbbd64c6308c7fe1d5fd3ff005397f76e38548f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -9,7 +9,7 @@ ## 导入模块 -```js +```ts import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; ``` @@ -53,22 +53,23 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen **示例**: - ```js - import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +```ts +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; - let myReason = 'test requestSuspendDelay'; - try { - let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspension delay will time out."); - }) - let id = delayInfo.requestId; - let time = delayInfo.actualDelayTime; - console.info("The requestId is: " + id); - console.info("The actualDelayTime is: " + time); - } catch (error) { - console.error(`requestSuspendDelay failed. code is ${error.code} message is ${error.message}`); - } - ``` +let myReason = 'test requestSuspendDelay'; +try { +let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); +}) +let id = delayInfo.requestId; +let time = delayInfo.actualDelayTime; +console.info("The requestId is: " + id); +console.info("The actualDelayTime is: " + time); +} catch (error) { +console.error(`requestSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); +} +``` ## backgroundTaskManager.getRemainingDelayTime @@ -102,22 +103,19 @@ getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): **示例**: - ```js - import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +```ts +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; - let id = 1; - try { - backgroundTaskManager.getRemainingDelayTime(id, (error, res) => { - if(error) { - console.error(`callback => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); - } else { - console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - } - }) - } catch (error) { - console.error(`callback => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); - } - ``` +let id = 1; +backgroundTaskManager.getRemainingDelayTime(id, (error: BusinessError, res: number) => { + if(error) { + console.error(`callback => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); + } else { + console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); + } +}) +``` ## backgroundTaskManager.getRemainingDelayTime @@ -155,20 +153,17 @@ getRemainingDelayTime(requestId: number): Promise<number> **示例**: - ```js - import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +```ts +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; - let id = 1; - try { - backgroundTaskManager.getRemainingDelayTime(id).then( res => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - }).catch( error => { - console.error(`promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); - }) - } catch (error) { +let id = 1; +backgroundTaskManager.getRemainingDelayTime(id).then((res: number) => { + console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); +}).catch((error: BusinessError) => { console.error(`promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); - } - ``` +}) +``` ## backgroundTaskManager.cancelSuspendDelay @@ -202,12 +197,13 @@ cancelSuspendDelay(requestId: number): void ```js import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import { BusinessError } from '@ohos.base'; let id = 1; try { backgroundTaskManager.cancelSuspendDelay(id); } catch (error) { - console.error(`cancelSuspendDelay failed. code is ${error.code} message is ${error.message}`); + console.error(`cancelSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } ``` @@ -249,9 +245,10 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want ```js import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; -function callback(error, data) { +function callback(error: BusinessError, data: void) { if (error) { console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); } else { @@ -260,8 +257,8 @@ function callback(error, data) { } export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let wantAgentInfo = { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + let wantAgentInfo: wantAgent.WantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", @@ -274,16 +271,16 @@ export default class EntryAbility extends UIAbility { }; try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { try { backgroundTaskManager.startBackgroundRunning(this.context, backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } }); } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } } }; @@ -332,11 +329,12 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want ```js import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let wantAgentInfo = { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + let wantAgentInfo: wantAgent.WantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", @@ -349,20 +347,20 @@ export default class EntryAbility extends UIAbility { }; try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { try { backgroundTaskManager.startBackgroundRunning(this.context, backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { console.info("Operation startBackgroundRunning succeeded"); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); }); } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } }); } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } } }; @@ -402,8 +400,9 @@ stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): vo ```js import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; -function callback(error, data) { +function callback(error: BusinessError, data: void) { if (error) { console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); } else { @@ -412,11 +411,11 @@ function callback(error, data) { } export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context, callback); } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } } }; @@ -461,17 +460,18 @@ stopBackgroundRunning(context: Context): Promise<void> ```js import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { console.info("Operation stopBackgroundRunning succeeded"); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); }); } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } } }; @@ -510,8 +510,9 @@ applyEfficiencyResources(request: EfficiencyResourcesRequest): void ```js import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; -let request = { +let request: backgroundTaskManager.EfficiencyResourcesRequest = { resourceTypes: backgroundTaskManager.ResourceType.CPU, isApply: true, timeOut: 0, @@ -523,7 +524,7 @@ try { backgroundTaskManager.applyEfficiencyResources(request); console.info("applyEfficiencyResources success. "); } catch (error) { - console.error(`applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); + console.error(`applyEfficiencyResources failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 70a2c5ef5456631a403c756e9a2fdfae38194897..4cf176b101a9191d34825cae2657aa0291dfd612 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -10,7 +10,7 @@ ## 导入模块 -```js +```ts import workScheduler from '@ohos.resourceschedule.workScheduler'; ``` @@ -42,8 +42,8 @@ startWork(work: WorkInfo): void **示例**: -```js - let workInfo = { +```ts + let workInfo: workScheduler.WorkInfo = { workId: 1, batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, isRepeat: false, @@ -61,7 +61,7 @@ startWork(work: WorkInfo): void workScheduler.startWork(workInfo); console.info('workschedulerLog startWork success'); } catch (error) { - console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); + console.error(`workschedulerLog startwork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } ``` @@ -93,8 +93,8 @@ stopWork(work: WorkInfo, needCancel?: boolean): void **示例**: -```js - let workInfo = { +```ts + let workInfo: workScheduler.WorkInfo = { workId: 1, batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, isRepeat: false, @@ -112,7 +112,7 @@ stopWork(work: WorkInfo, needCancel?: boolean): void workScheduler.stopWork(workInfo, false); console.info('workschedulerLog stopWork success'); } catch (error) { - console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); + console.error(`workschedulerLog stopWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } ``` @@ -144,20 +144,14 @@ getWorkStatus(workId: number, callback : AsyncCallback\): void **示例**: -```js - try{ - workScheduler.getWorkStatus(50, (error, res) => { - if (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); - } else { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - } - }); - } catch (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); - } +```ts + workScheduler.getWorkStatus(50, (error: BusinessError, res: workScheduler.WorkInfo) => { + if (error) { + console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog getWorkStatus success, ${JSON.stringify(res)}`); + } + }); ``` ## workScheduler.getWorkStatus @@ -193,18 +187,12 @@ getWorkStatus(workId: number): Promise\ **示例**: -```js - try{ - workScheduler.getWorkStatus(50).then((res) => { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - }).catch((error) => { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); - }) - } catch (error) { +```ts + workScheduler.getWorkStatus(50).then((res: workScheduler.WorkInfo) => { + console.info(`workschedulerLog getWorkStatus success, ${JSON.stringify(res)}`); + }).catch((error: BusinessError) => { console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); - } + }) ``` ## workScheduler.obtainAllWorks @@ -239,18 +227,14 @@ obtainAllWorks(callback : AsyncCallback\): Array\ **示例**: -```js - try{ - workScheduler.obtainAllWorks((error, res) =>{ - if (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - } - }); - } catch (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); - } +```ts + workScheduler.obtainAllWorks((error: BusinessError, res: Array) =>{ + if (error) { + console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); + } + }); ``` ## workScheduler.obtainAllWorks @@ -279,16 +263,12 @@ obtainAllWorks(): Promise\> **示例**: -```js - try{ - workScheduler.obtainAllWorks().then((res) => { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - }).catch((error) => { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); - }) - } catch (error) { +```ts + workScheduler.obtainAllWorks().then((res: Array) => { + console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); + }).catch((error: BusinessError) => { console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); - } + }) ``` ## workScheduler.stopAndClearWorks @@ -311,12 +291,12 @@ stopAndClearWorks(): void **示例**: -```js +```ts try{ workScheduler.stopAndClearWorks(); console.info(`workschedulerLog stopAndClearWorks success`); } catch (error) { - console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); + console.error(`workschedulerLog stopAndClearWorks failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); } ``` @@ -354,18 +334,14 @@ isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean **示例**: -```js - try{ - workScheduler.isLastWorkTimeOut(500, (error, res) =>{ - if (error) { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - } - }); - } catch (error) { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); - } +```ts + workScheduler.isLastWorkTimeOut(500, (error: BusinessError, res: boolean) =>{ + if (error) { + console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); + } + }); ``` ## workScheduler.isLastWorkTimeOut @@ -401,18 +377,14 @@ isLastWorkTimeOut(workId: number): Promise\ **示例**: -```js - try{ - workScheduler.isLastWorkTimeOut(500) - .then(res => { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - }) - .catch(error => { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); - } +```ts + workScheduler.isLastWorkTimeOut(500) + .then((res: boolean) => { + console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); + }) + .catch((error: BusinessError) => { + console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); + }); ``` ## WorkInfo diff --git a/zh-cn/application-dev/reference/apis/js-apis-rpc.md b/zh-cn/application-dev/reference/apis/js-apis-rpc.md index e27279f764852e15ded46f588584a9aeef2c115a..b328c7c0a5dfc3f5a8caac1fe44ea3275e8ec1bc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-rpc.md +++ b/zh-cn/application-dev/reference/apis/js-apis-rpc.md @@ -1289,8 +1289,8 @@ writeParcelable(val: Parcelable): void import { BusinessError } from '@ohos.base'; class MyParcelable implements rpc.Parcelable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor( num: number, str: string) { this.num = num; this.str = str; @@ -1346,8 +1346,8 @@ readParcelable(dataIn: Parcelable): void import { BusinessError } from '@ohos.base'; class MyParcelable implements rpc.Parcelable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -2595,7 +2595,7 @@ readException(): void import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -2680,8 +2680,8 @@ writeParcelableArray(parcelableArray: Parcelable[]): void import { BusinessError } from '@ohos.base'; class MyParcelable implements rpc.Parcelable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -2740,8 +2740,8 @@ readParcelableArray(parcelableArray: Parcelable[]): void import { BusinessError } from '@ohos.base'; class MyParcelable implements rpc.Parcelable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -4285,8 +4285,8 @@ writeSequenceable(val: Sequenceable): boolean ```ts class MySequenceable implements rpc.Sequenceable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -4332,8 +4332,8 @@ readSequenceable(dataIn: Sequenceable): boolean ```ts class MySequenceable implements rpc.Sequenceable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -5105,7 +5105,7 @@ readException(): void import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -5180,8 +5180,8 @@ writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean ```ts class MySequenceable implements rpc.Sequenceable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -5224,8 +5224,8 @@ readSequenceableArray(sequenceableArray: Sequenceable[]): void ```ts class MySequenceable implements rpc.Sequenceable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -5706,8 +5706,8 @@ marshalling(dataOut: MessageSequence): boolean ```ts class MyParcelable implements rpc.Parcelable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -5756,8 +5756,8 @@ unmarshalling(dataIn: MessageSequence): boolean ```ts class MyParcelable implements rpc.Parcelable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -5812,8 +5812,8 @@ marshalling(dataOut: MessageParcel): boolean ```ts class MySequenceable implements rpc.Sequenceable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -5862,8 +5862,8 @@ unmarshalling(dataIn: MessageParcel): boolean ```ts class MySequenceable implements rpc.Sequenceable { - num: number; - str: string; + num: number = 0; + str: string = ''; constructor(num: number, str: string) { this.num = num; this.str = str; @@ -5928,7 +5928,7 @@ asObject(): IRemoteObject import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6368,7 +6368,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6446,7 +6446,7 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6532,7 +6532,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6612,7 +6612,7 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6696,7 +6696,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6783,7 +6783,7 @@ getLocalInterface(interface: string): IRemoteBroker import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6852,7 +6852,7 @@ queryLocalInterface(interface: string): IRemoteBroker import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6917,7 +6917,7 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -6992,7 +6992,7 @@ addDeathRecipient(recipient: DeathRecipient, flags: number): boolean import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -7062,7 +7062,7 @@ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -7138,7 +7138,7 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -7209,7 +7209,7 @@ getDescriptor(): string import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -7271,7 +7271,7 @@ getInterfaceDescriptor(): string import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); @@ -7326,7 +7326,7 @@ isObjectDead(): boolean import Want from '@ohos.app.ability.Want'; import common from '@ohos.app.ability.common'; - let proxy: rpc.IRemoteobject | undefined = undefined; + let proxy: rpc.IRemoteObject | undefined = undefined; let connect: common.ConnectOptions = { onConnect: (elementName, remoteProxy) => { console.log("RpcClient: js onConnect called."); diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md old mode 100644 new mode 100755 index d96f01d128c2f9bf9d1193345456342cfc9b4fcb..450e78da0b054428bf5a22b601b9d6443cf2630a --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -1040,7 +1040,7 @@ try { ### ACCELEROMETER_UNCALIBRATED9+ -once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>): voidMAGNETIC_FIELD +once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>): void 获取一次未校准加速度传感器数据。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-stationary.md b/zh-cn/application-dev/reference/apis/js-apis-stationary.md index 959445052a71bbcdb09d1622481e24c1eaca4c34..cfe5a113668a18868ff839212986454dacd0ef2a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-stationary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-stationary.md @@ -10,7 +10,7 @@ ## 导入模块 -```js +```ts import stationary from '@ohos.stationary' ``` @@ -79,8 +79,8 @@ on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callba **示例:** -```js -var reportLatencyNs = 100; +```ts +let reportLatencyNs = 100; stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { console.log('data='+ JSON.stringify(data)); }) @@ -103,7 +103,7 @@ once(activity: ActivityType, callback: Callback<ActivityResponse>): void **示例:** -```js +```ts stationary.once('still', (data) => { console.log("data="+ JSON.stringify(data)); }) @@ -127,6 +127,6 @@ off(activity: ActivityType, event: ActivityEvent, callback?: Callback<Activit **示例:** -```js +```ts stationary.off('still', stationary.ActivityEvent.ENTER); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-app.md b/zh-cn/application-dev/reference/apis/js-apis-system-app.md index c749b29910531ed34200688f6a24dddf593e2c93..d1e4cbcca80659c684ddb568d655c0a4c1eab6ab 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-app.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-app.md @@ -9,7 +9,7 @@ ```ts -import app from '@system.app' +import app, { AppResponse } from '@system.app' ``` ## App @@ -33,9 +33,10 @@ static getInfo(): AppResponse **示例:** ```ts -export default { +import app, { AppResponse } from '@system.app' +export default class Info { getInfo() { - let info = app.getInfo() + let info:AppResponse = app.getInfo() console.log(JSON.stringify(info)) } } @@ -54,7 +55,8 @@ static terminate(): void **示例:** ```ts -export default { +import app, { AppResponse } from '@system.app' +export default class TerM { terminate() { app.terminate() } @@ -78,9 +80,9 @@ static setImageCacheCount(value: number): void ```ts // app.ets -import app from '@system.app' +import app, { AppResponse } from '@system.app' -export default { +export default class OnC { onCreate() { app.setImageCacheCount(100) // 设置解码后图片内存缓存上限为100张 console.info('Application onCreate') @@ -109,9 +111,9 @@ static setImageRawDataCacheSize(value: number): void ```ts // app.ets -import app from '@system.app' +import app, { AppResponse } from '@system.app' -export default { +export default class OnC { onCreate() { app.setImageRawDataCacheSize(104857600) // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B) @@ -141,9 +143,9 @@ static setImageFileCacheSize(value: number): void ```ts // app.ets -import app from '@system.app' +import app, { AppResponse } from '@system.app' -export default { +export default class OnC { onCreate() { app.setImageFileCacheSize(209715200) // 设置图片文件数据缓存上限为200MB (200MB=200*1024*1024B=209715200B) @@ -188,13 +190,14 @@ static requestFullWindow(options?: RequestFullWindowOptions): void **示例:** ```ts -export default { +import app, { AppResponse } from '@system.app' +export default class Req { requestFullWindow() { app.requestFullWindow({ duration: 200 }) } -} +} ``` ## AppResponse diff --git a/zh-cn/application-dev/reference/apis/js-apis-thermal.md b/zh-cn/application-dev/reference/apis/js-apis-thermal.md index f3e304c00c4b3e37c31303516de651fae43090d1..21027cf5284dc2a203f47f92191e36a128e66c21 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-thermal.md +++ b/zh-cn/application-dev/reference/apis/js-apis-thermal.md @@ -129,7 +129,7 @@ subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<ThermalLevel> | 是 | 回调函数。AsyncCallback只返回一个参数,为热档位信息,此时可能会产生告警,可通过`// @ts-ignore`进行抑制。 | +| callback | AsyncCallback<ThermalLevel> | 是 | 回调函数。AsyncCallback只返回一个参数,为热档位信息。| **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md index 16cc4ef9e057e9356a36aaa9932900872b0a7e4f..8708b091a36f13f3308df68686c87a5ee6929d47 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @@ -57,6 +57,8 @@ setDarkMode(mode: DarkMode, callback: AsyncCallback\): void **示例:** ```ts +import uiAppearance from '@ohos.uiAppearance' +import { BusinessError } from '@ohos.base'; try { uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK, (error) => { if (error) { @@ -105,10 +107,12 @@ setDarkMode(mode: DarkMode): Promise\; **示例:** ```ts +import uiAppearance from '@ohos.uiAppearance' +import { BusinessError } from '@ohos.base'; try { uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK).then(() => { console.info('Set dark-mode successfully.'); - }).catch((error) => { + }).catch((error:Error) => { console.error('Set dark-mode failed, ' + error.message); }); } catch (error) { @@ -145,9 +149,11 @@ getDarkMode(): DarkMode; **示例:** ```ts +import uiAppearance from '@ohos.uiAppearance' +import { BusinessError } from '@ohos.base'; try { let darkMode = uiAppearance.getDarkMode(); - console.info('Get dark-mode ' + mode); + console.info('Get dark-mode ' + darkMode); } catch (error) { let message = (error as BusinessError).message; console.error('Get dark-mode failed, ' + message); diff --git a/zh-cn/application-dev/reference/apis/js-apis-uitest.md b/zh-cn/application-dev/reference/apis/js-apis-uitest.md index 64f8f48376eec85566706e143c267af6cfe3f127..f5183f08c418a1a13175cc47075d435d21a27ae5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uitest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uitest.md @@ -17,9 +17,9 @@ UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要 >本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -## 导入模块 +## 导入模块 -```js +```ts import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix, UiDirection, MouseButton, UIElementInfo, UIEventObserver} from '@ohos.UiTest'; ``` @@ -158,7 +158,8 @@ UI事件的相关信息。 UiTest框架在API 9中,通过On类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
On提供的API能力具有以下几个特点:
1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。
2、控件属性支持多种匹配模式。
3、支持控件绝对定位,相对定位,可通过[ON.isBefore](#isbefore)和[ON.isAfter](#isafter)等API限定邻近控件特征进行辅助定位。
On类提供的所有API均为同步接口,建议使用者通过静态构造器ON来链式创建On对象。 -```js +```ts +import { ON } from '@ohos.UiTest'; ON.text('123').type('button'); ``` @@ -185,11 +186,11 @@ text(txt: string, pattern?: MatchPattern): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.text('123'); // 使用静态构造器ON创建On对象,指定目标控件的text属性。 ``` - ### id9+ id(id: string): On @@ -212,7 +213,8 @@ id(id: string): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.id('123'); // 使用静态构造器ON创建On对象,指定目标控件的id属性。 ``` @@ -239,7 +241,8 @@ type(tp: string): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.type('button'); // 使用静态构造器ON创建On对象,指定目标控件的控件类型属性。 ``` @@ -266,7 +269,8 @@ clickable(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.clickable(true); // 使用静态构造器ON创建On对象,指定目标控件的可点击状态属性。 ``` @@ -292,7 +296,8 @@ longClickable(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.longClickable(true); // 使用静态构造器ON创建On对象,指定目标控件的可长按点击状态属性。 ``` @@ -319,7 +324,8 @@ scrollable(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.scrollable(true); // 使用静态构造器ON创建On对象,指定目标控件的可滑动状态属性。 ``` @@ -345,7 +351,8 @@ enabled(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.enabled(true); // 使用静态构造器ON创建On对象,指定目标控件的使能状态属性。 ``` @@ -371,7 +378,8 @@ focused(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.focused(true); // 使用静态构造器ON创建On对象,指定目标控件的获焦状态属性。 ``` @@ -397,7 +405,8 @@ selected(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.selected(true); // 使用静态构造器ON创建On对象,指定目标控件的被选中状态属性。 ``` @@ -423,7 +432,8 @@ checked(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.checked(true); // 使用静态构造器ON创建On对象,指定目标控件的被勾选状态属性 ``` @@ -449,7 +459,8 @@ checkable(b?: boolean): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.checkable(true); // 使用静态构造器ON创建On对象,指定目标控件的能否被勾选状态属性。 ``` @@ -475,7 +486,8 @@ isBefore(on: On): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.isBefore(ON.text('123')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之前。 ``` @@ -501,7 +513,8 @@ isAfter(on: On): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.isAfter(ON.text('123')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之后。 ``` @@ -527,7 +540,8 @@ within(on: On): On **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.within(ON.type('List')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之内。 ``` @@ -553,7 +567,8 @@ inWindow(bundleName: string): On; **示例:** -```js +```ts +import { ON } from '@ohos.UiTest'; let on = ON.inWindow('com.uitestScene.acts'); // 使用静态构造器ON创建On对象,指定目标控件位于给出的应用窗口内。 ``` @@ -581,7 +596,8 @@ click(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -608,7 +624,8 @@ doubleClick(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -635,7 +652,8 @@ longClick(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -668,7 +686,8 @@ getId(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -701,7 +720,8 @@ getText(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -734,7 +754,8 @@ getType(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -767,7 +788,8 @@ getBounds(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -800,7 +822,8 @@ getBoundsCenter(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -833,7 +856,8 @@ isClickable(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -847,7 +871,7 @@ async function demo() { ### isLongClickable9+ -isLongClickable(): Promise\ +isLongClickable(): Promise\ 获取控件对象可长按点击属性。 @@ -870,7 +894,8 @@ isLongClickable(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -907,7 +932,8 @@ isChecked(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let checkBox = await driver.findComponent(ON.type('Checkbox')); @@ -944,7 +970,8 @@ isCheckable(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let checkBox = await driver.findComponent(ON.type('Checkbox')); @@ -981,7 +1008,8 @@ isScrollable(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let scrollBar = await driver.findComponent(ON.scrollable(true)); @@ -1019,7 +1047,8 @@ isEnabled(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -1057,7 +1086,8 @@ isFocused(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -1094,7 +1124,8 @@ isSelected(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -1131,7 +1162,8 @@ inputText(text: string): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let text = await driver.findComponent(ON.text('hello world')); @@ -1156,7 +1188,8 @@ clearText(): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let text = await driver.findComponent(ON.text('hello world')); @@ -1195,7 +1228,8 @@ scrollSearch(on: On): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let scrollBar = await driver.findComponent(ON.type('Scroll')); @@ -1228,7 +1262,8 @@ scrollToTop(speed?: number): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let scrollBar = await driver.findComponent(ON.type('Scroll')); @@ -1261,7 +1296,8 @@ scrollToBottom(speed?: number): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let scrollBar = await driver.findComponent(ON.type('Scroll')); @@ -1294,7 +1330,8 @@ dragTo(target: Component): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.type('button')); @@ -1328,7 +1365,8 @@ pinchOut(scale: number): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let image = await driver.findComponent(ON.type('image')); @@ -1361,7 +1399,8 @@ pinchIn(scale: number): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let image = await driver.findComponent(ON.type('image')); @@ -1398,7 +1437,8 @@ static create(): Driver **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); } @@ -1428,7 +1468,8 @@ Driver对象在给定的时间内延时。 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.delayMs(1000); @@ -1465,7 +1506,8 @@ findComponent(on: On): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.findComponent(ON.text('next page')); @@ -1502,7 +1544,8 @@ findComponents(on: On): Promise\> **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let buttonList = await driver.findComponents(ON.text('next page')); @@ -1539,7 +1582,8 @@ findWindow(filter: WindowFilter): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -1577,7 +1621,8 @@ waitForComponent(on: On, time: number): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let button = await driver.waitForComponent(ON.text('next page'),500); @@ -1609,7 +1654,8 @@ assertComponentExist(on: On): Promise\ **示例:** -```js +```ts +import { Driver, ON } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.assertComponentExist(ON.text('next page')); @@ -1634,7 +1680,8 @@ Driver对象进行点击BACK键的操作。 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.pressBack(); @@ -1665,7 +1712,8 @@ Driver对象采取如下操作:传入key值实现模拟点击对应按键的 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.triggerKey(123); @@ -1698,7 +1746,8 @@ Driver对象通过给定的key值,找到对应组合键并点击。例如,Ke **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.triggerCombineKeys(2072, 2047, 2035); @@ -1731,7 +1780,8 @@ Driver对象采取如下操作:在目标坐标点单击。 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.click(100,100); @@ -1763,7 +1813,8 @@ Driver对象采取如下操作:在目标坐标点双击。 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.doubleClick(100,100); @@ -1795,7 +1846,8 @@ Driver对象采取如下操作:在目标坐标点长按。 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.longClick(100,100); @@ -1830,7 +1882,8 @@ Driver对象采取如下操作:从起始坐标点滑向目的坐标点。 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.swipe(100,100,200,200,600); @@ -1865,7 +1918,8 @@ Driver对象采取如下操作:从起始坐标点拖拽至目的坐标点。 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.drag(100,100,200,200,600); @@ -1902,7 +1956,8 @@ Driver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的 **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.screenCap('/data/storage/el2/base/cache/1.png'); @@ -1933,7 +1988,8 @@ setDisplayRotation(rotation: DisplayRotation): Promise\ **示例:** -```js +```ts +import { Driver, DisplayRotation } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.setDisplayRotation(DisplayRotation.ROTATION_180); @@ -1964,7 +2020,8 @@ getDisplayRotation(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let rotation = await driver.getDisplayRotation(); @@ -1995,7 +2052,8 @@ setDisplayRotationEnabled(enabled: boolean): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.setDisplayRotationEnabled(false); @@ -2026,7 +2084,8 @@ getDisplaySize(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let size = await driver.getDisplaySize(); @@ -2057,7 +2116,8 @@ getDisplayDensity(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let density = await driver.getDisplayDensity(); @@ -2082,7 +2142,8 @@ wakeUpDisplay(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.wakeUpDisplay(); @@ -2107,7 +2168,8 @@ pressHome(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.pressHome(); @@ -2145,7 +2207,8 @@ waitForIdle(idleTime: number, timeout: number): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let idled = await driver.waitForIdle(4000,5000); @@ -2179,7 +2242,8 @@ fling(from: Point, to: Point, stepLen: number, speed: number): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.fling({x: 500, y: 480},{x: 450, y: 480},5,600); @@ -2217,7 +2281,8 @@ injectMultiPointerAction(pointers: PointerMatrix, speed?: number): Promise\; **示例:** -```js +```ts +import { Driver, UiDirection } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.fling(UiDirection.DOWN, 10000); @@ -2294,7 +2360,8 @@ screenCapture(savePath: string, rect?: Rect): Promise\; **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.screenCapture('/data/storage/el2/base/cache/1.png', {left: 0, top: 0, right: 100, bottom: 100}); @@ -2328,7 +2395,8 @@ mouseClick(p: Point, btnId: MouseButton, key1?: number, key2?: number): Promise\ **示例:** -```js +```ts +import { Driver,MouseButton } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.mouseClick({x:248, y:194}, MouseButton.MOUSE_BUTTON_LEFT, 2072); @@ -2363,7 +2431,8 @@ mouseScroll(p: Point, down: boolean, d: number, key1?: number, key2?: number): P **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.mouseScroll({x:360, y:640}, true, 30, 2072) @@ -2394,7 +2463,8 @@ mouseMoveTo(p: Point): Promise\; **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); await driver.mouseMoveTo({x:100, y:100}) @@ -2425,7 +2495,8 @@ createUIEventObserver(): UIEventObserver; **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let observer = await driver.createUIEventObserver() @@ -2459,7 +2530,8 @@ static create(fingers: number, steps: number): PointerMatrix **示例:** -```js +```ts +import { PointerMatrix } from '@ohos.UiTest'; async function demo() { let pointerMatrix = PointerMatrix.create(2,3); } @@ -2483,7 +2555,8 @@ setPoint(finger: number, step: number, point: Point): void **示例:** -```js +```ts +import { PointerMatrix } from '@ohos.UiTest'; async function demo() { let pointers = PointerMatrix.create(2,3); pointers.setPoint(0,0,{x:230,y:480}); @@ -2525,7 +2598,8 @@ getBundleName(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2558,7 +2632,8 @@ getBounds(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2591,7 +2666,8 @@ getTitle(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2624,7 +2700,8 @@ getWindowMode(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2657,7 +2734,8 @@ isFocused(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2690,7 +2768,8 @@ isActived(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2717,7 +2796,8 @@ focus(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2752,7 +2832,8 @@ moveTo(x: number, y: number): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2788,7 +2869,8 @@ resize(wide: number, height: number, direction: ResizeDirection): Promise\ **示例:** -```js +```ts +import { Driver, ResizeDirection } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2816,7 +2898,8 @@ split(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2844,7 +2927,8 @@ maximize(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2872,7 +2956,8 @@ minimize(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2900,7 +2985,8 @@ resume(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2928,7 +3014,8 @@ close(): Promise\ **示例:** -```js +```ts +import { Driver } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let window = await driver.findWindow({actived: true}); @@ -2957,11 +3044,12 @@ once(type: 'toastShow', callback: Callback\):void; **示例:** -```js +```ts +import { Driver, UIElementInfo } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let observer = await driver.createUIEventObserver() - let callback = (UIElementInfo)=>{ + let callback = (UIElementInfo: UIElementInfo)=>{ console.info(UIElementInfo.bundleName) console.info(UIElementInfo.text) console.info(UIElementInfo.type) @@ -2987,11 +3075,12 @@ once(type: 'dialogShow', callback: Callback\): void; **示例:** -```js +```ts +import { Driver, UIElementInfo } from '@ohos.UiTest'; async function demo() { let driver = Driver.create(); let observer = await driver.createUIEventObserver() - let callback = (UIElementInfo)=>{ + let callback = (UIElementInfo: UIElementInfo)=>{ console.info(UIElementInfo.bundleName) console.info(UIElementInfo.text) console.info(UIElementInfo.type) @@ -3007,7 +3096,8 @@ By提供的API能力具有以下几个特点:
1、支持单属性匹配和多 从API version 9开始不再维护,建议使用[On9+](#on9)。 -```js +```ts +import { BY } from '@ohos.UiTest'; BY.text('123').type('button'); ``` @@ -3036,7 +3126,8 @@ text(txt: string, pattern?: MatchPattern): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.text('123'); // 使用静态构造器BY创建by对象,指定目标控件的text属性。 ``` @@ -3065,7 +3156,8 @@ key(key: string): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.key('123'); // 使用静态构造器BY创建by对象,指定目标控件的key值属性。 ``` @@ -3094,7 +3186,8 @@ id(id: number): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.id(123); // 使用静态构造器BY创建by对象,指定目标控件的id属性。 ``` @@ -3123,7 +3216,8 @@ type(tp: string): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.type('button'); // 使用静态构造器BY创建by对象,指定目标控件的控件类型属性。 ``` @@ -3152,7 +3246,8 @@ clickable(b?: boolean): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.clickable(true); // 使用静态构造器BY创建by对象,指定目标控件的可点击状态属性。 ``` @@ -3181,7 +3276,8 @@ scrollable(b?: boolean): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.scrollable(true); // 使用静态构造器BY创建by对象,指定目标控件的可滑动状态属性。 ``` @@ -3209,7 +3305,8 @@ enabled(b?: boolean): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.enabled(true); // 使用静态构造器BY创建by对象,指定目标控件的使能状态属性。 ``` @@ -3237,7 +3334,8 @@ focused(b?: boolean): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.focused(true); // 使用静态构造器BY创建by对象,指定目标控件的获焦状态属性。 ``` @@ -3265,7 +3363,8 @@ selected(b?: boolean): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.selected(true); // 使用静态构造器BY创建by对象,指定目标控件的被选中状态属性。 ``` @@ -3293,7 +3392,8 @@ isBefore(by: By): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.isBefore(BY.text('123')); // 使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之前。 ``` @@ -3321,7 +3421,8 @@ isAfter(by: By): By **示例:** -```js +```ts +import { BY } from '@ohos.UiTest'; let by = BY.isAfter(BY.text('123')); // 使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之后。 ``` @@ -3344,7 +3445,8 @@ click(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3364,7 +3466,8 @@ doubleClick(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3384,7 +3487,8 @@ longClick(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3410,7 +3514,8 @@ getId(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3436,7 +3541,8 @@ getKey(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3462,7 +3568,8 @@ getText(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3488,7 +3595,8 @@ getType(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3514,7 +3622,8 @@ isClickable(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3544,7 +3653,8 @@ isScrollable(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let scrollBar = await driver.findComponent(BY.scrollable(true)); @@ -3575,7 +3685,8 @@ isEnabled(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3606,7 +3717,8 @@ isFocused(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3636,7 +3748,8 @@ isSelected(): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.type('button')); @@ -3666,7 +3779,8 @@ inputText(text: string): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let text = await driver.findComponent(BY.text('hello world')); @@ -3698,7 +3812,8 @@ scrollSearch(by: By): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let scrollBar = await driver.findComponent(BY.type('Scroll')); @@ -3731,7 +3846,8 @@ static create(): UiDriver **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); } @@ -3755,7 +3871,8 @@ UiDriver对象在给定的时间内延时。 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.delayMs(1000); @@ -3786,7 +3903,8 @@ findComponent(by: By): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let button = await driver.findComponent(BY.text('next page')); @@ -3817,7 +3935,8 @@ findComponents(by: By): Promise\> **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); let buttonList = await driver.findComponents(BY.text('next page')); @@ -3851,7 +3970,8 @@ assertComponentExist(by: By): Promise\ **示例:** -```js +```ts +import { UiDriver, BY } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.assertComponentExist(BY.text('next page')); @@ -3870,7 +3990,8 @@ UiDriver对象进行点击BACK键的操作。 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.pressBack(); @@ -3895,7 +4016,8 @@ UiDriver对象采取如下操作:通过key值找到对应键并点击。 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.triggerKey(123); @@ -3922,7 +4044,8 @@ UiDriver对象采取如下操作:在目标坐标点单击。 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.click(100,100); @@ -3948,7 +4071,8 @@ UiDriver对象采取如下操作:在目标坐标点双击。 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.doubleClick(100,100); @@ -3974,7 +4098,8 @@ UiDriver对象采取如下操作:在目标坐标点长按下鼠标左键。 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.longClick(100,100); @@ -4002,7 +4127,8 @@ UiDriver对象采取如下操作:从给出的起始坐标点滑向给出的目 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.swipe(100,100,200,200); @@ -4033,9 +4159,10 @@ UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的 **示例:** -```js +```ts +import { UiDriver } from '@ohos.UiTest'; async function demo() { let driver = UiDriver.create(); await driver.screenCap('/data/storage/el2/base/cache/1.png'); } -``` +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md b/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md index 5c691506b9bc0e198a9596751e015cc7a697c834..c26124dda4987c523dce6dcf364b7e38821e2b1b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -72,12 +72,12 @@ setSurfaceId(surfaceId: string): void; import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; // 该surfaceId应该从XComponent控件获取,此处仅用作示例。 -let surfaceId = "123456"; +let surfaceId = '123456'; let manager = new userIAM_faceAuth.FaceAuthManager(); try { - manager.setSurfaceId(surfaceId); - console.info("set surface id success"); + manager.setSurfaceId(surfaceId); + console.info('set surface id success'); } catch (e) { - console.error("set surface id failed, error = " + e); + console.error('set surface id failed, error = ' + e); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md b/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md index d44f7b67989499701a4ae7d514cc0b01ae42f7a2..98cf0d0e691c52d4169fafb07bc790c23d4876d4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -31,11 +31,11 @@ import userIAM_userAuth from '@ohos.userIAM.userAuth'; **系统能力**:SystemCapability.UserIAM.UserAuth.Core -| 名称 | 类型 | 必填 | 说明 | -| -------------- | ---------------------------------- | ---- | ------------------------------------------------------ | -| challenge | Uint8Array | 是 | 挑战值,用来防重放攻击。最大长度为32字节,可以填null。 | -| authType | [UserAuthType](#userauthtype8)[] | 是 | 认证类型列表,用来指定用户认证界面提供的认证方法。 | -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 认证信任等级。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| challenge | Uint8Array | 是 | 挑战值,用来防重放攻击。最大长度为32字节,可传Uint8Array([])。 | +| authType | [UserAuthType](#userauthtype8)[] | 是 | 认证类型列表,用来指定用户认证界面提供的认证方法。 | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 认证信任等级。 | ## WidgetParam10+ @@ -85,27 +85,26 @@ onResult(result: UserAuthResult): void ```js import userAuth from '@ohos.userIAM.userAuth'; -const authParam = { - challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), - authType: [userAuth.UserAuthType.PIN], - authTrustLevel: 10000, +const authParam : userAuth.AuthParam = { + challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), + authType: [userAuth.UserAuthType.PIN], + authTrustLevel: userAuth.AuthTrustLevel.ATL1, }; -const widgetParam = { - title: '请输入密码', - navigationButtonText: '返回', - windowMode: userAuth.WindowModeType.DIALOG_BOX, +const widgetParam :userAuth.WidgetParam = { + title: '请输入密码', + navigationButtonText: '返回', }; try { - let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); - console.log('get userAuth instance success'); - userAuthInstance.on('result', { - onResult (result) { - console.log('userAuthInstance callback result = ' + JSON.stringify(result)); - } - }); - console.log('auth on success'); + let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); + console.log('get userAuth instance success'); + userAuthInstance.on('result', { + onResult (result) { + console.log('userAuthInstance callback result = ' + JSON.stringify(result)); + } + }); + console.log('auth on success'); } catch (error) { - console.log('auth catch error: ' + JSON.stringify(error)); + console.log('auth catch error: ' + JSON.stringify(error)); } ``` @@ -143,27 +142,26 @@ on(type: 'result', callback: IAuthCallback): void ```js import userAuth from '@ohos.userIAM.userAuth'; -const authParam = { - challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), - authType: [userAuth.UserAuthType.PIN], - authTrustLevel: 10000, +const authParam : userAuth.AuthParam = { + challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), + authType: [userAuth.UserAuthType.PIN], + authTrustLevel: userAuth.AuthTrustLevel.ATL1, }; -const widgetParam = { - title: '请输入密码', - navigationButtonText: '返回', - windowMode: userAuth.WindowModeType.DIALOG_BOX, +const widgetParam :userAuth.WidgetParam = { + title: '请输入密码', + navigationButtonText: '返回', }; try { - let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); - console.log('get userAuth instance success'); - userAuthInstance.on('result', { - onResult (result) { - console.log('userAuthInstance callback result = ' + JSON.stringify(result)); - } - }); - console.log('auth on success'); + let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); + console.log('get userAuth instance success'); + userAuthInstance.on('result', { + onResult (result) { + console.log('userAuthInstance callback result = ' + JSON.stringify(result)); + } + }); + console.log('auth on success'); } catch (error) { - console.log('auth catch error: ' + JSON.stringify(error)); + console.log('auth catch error: ' + JSON.stringify(error)); } ``` @@ -198,27 +196,26 @@ off(type: 'result', callback?: IAuthCallback): void ```js import userAuth from '@ohos.userIAM.userAuth'; -const authParam = { - challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), - authType: [userAuth.UserAuthType.PIN], - authTrustLevel: 10000, +const authParam : userAuth.AuthParam = { + challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), + authType: [userAuth.UserAuthType.PIN], + authTrustLevel: userAuth.AuthTrustLevel.ATL1, }; -const widgetParam = { - title: '请输入密码', - navigationButtonText: '返回', - windowMode: userAuth.WindowModeType.DIALOG_BOX, +const widgetParam :userAuth.WidgetParam = { + title: '请输入密码', + navigationButtonText: '返回', }; try { - let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); - console.log('get userAuth instance success'); - userAuthInstance.off('result', { - onResult (result) { - console.log('auth off result: ' + JSON.stringify(result)); - } - }); - console.log('auth off success'); + let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); + console.log('get userAuth instance success'); + userAuthInstance.off('result', { + onResult (result) { + console.log('auth off result: ' + JSON.stringify(result)); + } + }); + console.log('auth off success'); } catch (error) { - console.log('auth catch error: ' + JSON.stringify(error)); + console.log('auth catch error: ' + JSON.stringify(error)); } ``` @@ -256,23 +253,22 @@ start(): void ```js import userAuth from '@ohos.userIAM.userAuth'; -const authParam = { - challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), - authType: [userAuth.UserAuthType.PIN], - authTrustLevel: 10000, +const authParam : userAuth.AuthParam = { + challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), + authType: [userAuth.UserAuthType.PIN], + authTrustLevel: userAuth.AuthTrustLevel.ATL1, }; -const widgetParam = { - title: '请输入密码', - navigationButtonText: '返回', - windowMode: userAuth.WindowModeType.DIALOG_BOX, +const widgetParam :userAuth.WidgetParam = { + title: '请输入密码', + navigationButtonText: '返回', }; try { - let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); - console.log('get userAuth instance success'); - userAuthInstance.start(); - console.log('auth start success'); + let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); + console.log('get userAuth instance success'); + userAuthInstance.start(); + console.log('auth start success'); } catch (error) { - console.log('auth catch error: ' + JSON.stringify(error)); + console.log('auth catch error: ' + JSON.stringify(error)); } ``` @@ -301,23 +297,22 @@ cancel(): void ```js import userAuth from '@ohos.userIAM.userAuth'; -const authParam = { - challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), - authType: [userAuth.UserAuthType.PIN], - authTrustLevel: 10000, +const authParam : userAuth.AuthParam = { + challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), + authType: [userAuth.UserAuthType.PIN], + authTrustLevel: userAuth.AuthTrustLevel.ATL1, }; -const widgetParam = { - title: '请输入密码', - navigationButtonText: '返回', - windowMode: userAuth.WindowModeType.DIALOG_BOX, +const widgetParam :userAuth.WidgetParam = { + title: '请输入密码', + navigationButtonText: '返回', }; try { - let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); - console.log('get userAuth instance success'); - userAuthInstance.cancel(); - console.log('auth cancel success'); + let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); + console.log('get userAuth instance success'); + userAuthInstance.cancel(); + console.log('auth cancel success'); } catch (error) { - console.log('auth catch error: ' + JSON.stringify(error)); + console.log('auth catch error: ' + JSON.stringify(error)); } ``` @@ -361,21 +356,20 @@ getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthIns ```js import userAuth from '@ohos.userIAM.userAuth'; -const authParam = { - challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), - authType: [userAuth.UserAuthType.PIN], - authTrustLevel: 10000, +const authParam : userAuth.AuthParam = { + challenge: new Uint8Array([49, 49, 49, 49, 49, 49]), + authType: [userAuth.UserAuthType.PIN], + authTrustLevel: userAuth.AuthTrustLevel.ATL1, }; -const widgetParam = { - title: '请输入密码', - navigationButtonText: '返回', - windowMode: userAuth.WindowModeType.DIALOG_BOX, +const widgetParam :userAuth.WidgetParam = { + title: '请输入密码', + navigationButtonText: '返回', }; try { - let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); - console.log('get userAuth instance success'); + let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam); + console.log('get userAuth instance success'); } catch (error) { - console.log('auth catch error: ' + JSON.stringify(error)); + console.log('auth catch error: ' + JSON.stringify(error)); } ``` @@ -426,21 +420,30 @@ sendNotice(noticeType: NoticeType, eventData: string): void ```js import userAuth from '@ohos.userIAM.userAuth'; +interface EventData { + widgetContextId: number; + event: string; + version: string; + payload: PayLoad; +} +interface PayLoad { + type: Object[]; +} try { - const eventData = { - widgetContextId: 123456, - event: 'EVENT_AUTH_TYPE_READY', - version: '1', - payload: { - type: ['pin'] - }, - }; - const jsonEventData = JSON.stringify(eventData); - let noticeType = userAuth.NoticeType.WIDGET_NOTICE; - userAuth.sendNotice(noticeType, jsonEventData); - console.log('sendNotice success'); + const eventData : EventData = { + widgetContextId: 123456, + event: 'EVENT_AUTH_TYPE_READY', + version: '1', + payload: { + type: ['pin'] + } as PayLoad, + }; + const jsonEventData = JSON.stringify(eventData); + let noticeType = userAuth.NoticeType.WIDGET_NOTICE; + userAuth.sendNotice(noticeType, jsonEventData); + console.log('sendNotice success'); } catch (error) { - console.log('sendNotice catch error: ' + JSON.stringify(error)); + console.log('sendNotice catch error: ' + JSON.stringify(error)); } ``` @@ -481,16 +484,16 @@ import userAuth from '@ohos.userIAM.userAuth'; const userAuthWidgetMgrVersion = 1; try { - let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); - console.log('get userAuthWidgetMgr instance success'); - userAuthWidgetMgr.on('command', { - sendCommand(cmdData) { - console.log('The cmdData is ' + cmdData); - } - }) - console.log('subscribe authentication event success'); + let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); + console.log('get userAuthWidgetMgr instance success'); + userAuthWidgetMgr.on('command', { + sendCommand(cmdData) { + console.log('The cmdData is ' + cmdData); + } + }) + console.log('subscribe authentication event success'); } catch (error) { - console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); + console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); } ``` @@ -527,16 +530,16 @@ import userAuth from '@ohos.userIAM.userAuth'; const userAuthWidgetMgrVersion = 1; try { - let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); - console.log('get userAuthWidgetMgr instance success'); - userAuthWidgetMgr.off('command', { - sendCommand(cmdData) { - console.log('The cmdData is ' + cmdData); - } - }) - console.log('cancel subscribe authentication event success'); + let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); + console.log('get userAuthWidgetMgr instance success'); + userAuthWidgetMgr.off('command', { + sendCommand(cmdData) { + console.log('The cmdData is ' + cmdData); + } + }) + console.log('cancel subscribe authentication event success'); } catch (error) { - console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); + console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); } ``` @@ -585,10 +588,10 @@ import userAuth from '@ohos.userIAM.userAuth'; let userAuthWidgetMgrVersion = 1; try { - let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); - console.log('get userAuthWidgetMgr instance success'); + let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); + console.log('get userAuthWidgetMgr instance success'); } catch (error) { - console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); + console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); } ``` @@ -619,16 +622,16 @@ import userAuth from '@ohos.userIAM.userAuth'; const userAuthWidgetMgrVersion = 1; try { - let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); - console.log('get userAuthWidgetMgr instance success'); - userAuthWidgetMgr.on('command', { - sendCommand(cmdData) { - console.log('The cmdData is ' + cmdData); - } - }) - console.log('subscribe authentication event success'); + let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion); + console.log('get userAuthWidgetMgr instance success'); + userAuthWidgetMgr.on('command', { + sendCommand(cmdData) { + console.log('The cmdData is ' + cmdData); + } + }) + console.log('subscribe authentication event success'); } catch (error) { - console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); + console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error)); } ``` @@ -706,41 +709,41 @@ let authType = userIAM_userAuth.UserAuthType.FACE; let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; // 通过callback获取认证结果 try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - console.log("authV9 result " + result.result); - console.log("authV9 token " + result.token); - console.log("authV9 remainAttempts " + result.remainAttempts); - console.log("authV9 lockoutDuration " + result.lockoutDuration); - } - }); - auth.start(); - console.log("authV9 start success"); + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on('result', { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + console.log('authV9 result ' + result.result); + console.log('authV9 token ' + result.token); + console.log('authV9 remainAttempts ' + result.remainAttempts); + console.log('authV9 lockoutDuration ' + result.lockoutDuration); + } + } as userIAM_userAuth.AuthEvent); + auth.start(); + console.log('authV9 start success'); } catch (error) { - console.log("authV9 error = " + error); - // do error + console.log('authV9 error = ' + error); + // do error } // 通过callback获取认证过程中的提示信息 try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("tip", { - callback : (result : userIAM_userAuth.TipInfo) => { - switch (result.tip) { - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: - // do something; - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: - // do something; - default: - // do others - } - } - }); - auth.start(); - console.log("authV9 start success"); + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on('tip', { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // do something; + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // do something; + default: + // do others + } + } + } as userIAM_userAuth.AuthEvent); + auth.start(); + console.log('authV9 start success'); } catch (error) { - console.log("authV9 error = " + error); - // do error + console.log('authV9 error = ' + error); + // do error } ``` @@ -790,34 +793,34 @@ let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); let authType = userIAM_userAuth.UserAuthType.FACE; let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - // 订阅认证结果 - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - console.log("authV9 result " + result.result); - console.log("authV9 token " + result.token); - console.log("authV9 remainAttempts " + result.remainAttempts); - console.log("authV9 lockoutDuration " + result.lockoutDuration); - } - }); - // 订阅认证过程中的提示信息 - auth.on("tip", { - callback : (result : userIAM_userAuth.TipInfo) => { - switch (result.tip) { - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: - // do something; - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: - // do something; - default: - // do others - } - } - }); - auth.start(); - console.log("authV9 start success"); + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + // 订阅认证结果 + auth.on('result', { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + console.log('authV9 result ' + result.result); + console.log('authV9 token ' + result.token); + console.log('authV9 remainAttempts ' + result.remainAttempts); + console.log('authV9 lockoutDuration ' + result.lockoutDuration); + } + }); + // 订阅认证过程中的提示信息 + auth.on('tip', { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // do something; + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // do something; + default: + // do others + } + } + } as userIAM_userAuth.AuthEvent); + auth.start(); + console.log('authV9 start success'); } catch (error) { - console.log("authV9 error = " + error); - // do error + console.log('authV9 error = ' + error); + // do error } ``` @@ -856,34 +859,23 @@ import userIAM_userAuth from '@ohos.userIAM.userAuth'; let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); let authType = userIAM_userAuth.UserAuthType.FACE; let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; -let auth; -try { - auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - console.log("get auth instance success"); -} catch (error) { - console.log("get auth instance failed" + error); -} - try { - // 订阅认证结果 - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - console.log("authV9 result " + result.result); - console.log("authV9 token " + result.token); - console.log("authV9 remainAttempts " + result.remainAttempts); - console.log("authV9 lockoutDuration " + result.lockoutDuration); - } - }); - console.log("subscribe authentication event success"); -} catch (error) { - console.log("subscribe authentication event failed " + error); -} -// 取消订阅认证结果 -try { - auth.off("result"); - console.info("cancel subscribe authentication event success"); + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + // 订阅认证结果 + auth.on('result', { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + console.log('authV9 result ' + result.result); + console.log('authV9 token ' + result.token); + console.log('authV9 remainAttempts ' + result.remainAttempts); + console.log('authV9 lockoutDuration ' + result.lockoutDuration); + } + }); + // 取消订阅结果 + auth.off('result'); + console.info('cancel subscribe authentication event success'); } catch (error) { - console.info("cancel subscribe authentication event failed, error = " + error); + console.info('cancel subscribe authentication event failed, error =' + error); + // do error } ``` @@ -931,11 +923,11 @@ let authType = userIAM_userAuth.UserAuthType.FACE; let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - console.info("authV9 start auth success"); + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.start(); + console.info('authV9 start auth success'); } catch (error) { - console.info("authV9 start auth failed, error = " + error); + console.info('authV9 start auth failed, error = ' + error); } ``` @@ -975,11 +967,11 @@ let authType = userIAM_userAuth.UserAuthType.FACE; let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.cancel(); - console.info("cancel auth success"); + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.cancel(); + console.info('cancel auth success'); } catch (error) { - console.info("cancel auth failed, error = " + error); + console.info('cancel auth failed, error = ' + error); } ``` @@ -1001,7 +993,7 @@ getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel | 参数名 | 类型 | 必填 | 说明 | | -------------- | ---------------------------------------- | ---- | ------------------------ | -| challenge | Uint8Array | 是 | 挑战值,最大长度为32字节,可以填null。 | +| challenge | Uint8Array | 是 | 挑战值,最大长度为32字节,可以传Uint8Array([])。 | | authType | [UserAuthType](#userauthtype8) | 是 | 认证类型,当前支持FACE。 | | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 认证信任等级。 | @@ -1032,10 +1024,10 @@ let authType = userIAM_userAuth.UserAuthType.FACE; let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - console.info("get auth instance success"); + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.info('let auth instance success'); } catch (error) { - console.info("get auth instance success failed, error = " + error); + console.info('get auth instance success failed, error = ' + error); } ``` @@ -1075,10 +1067,10 @@ getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): vo import userIAM_userAuth from '@ohos.userIAM.userAuth'; try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); + userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + console.info('current auth trust level is supported'); } catch (error) { - console.info("current auth trust level is not supported, error = " + error); + console.info('current auth trust level is not supported, error = ' + error); } ``` @@ -1157,7 +1149,7 @@ import userIAM_userAuth from '@ohos.userIAM.userAuth'; let auth = new userIAM_userAuth.UserAuth(); let version = auth.getVersion(); -console.info("auth version = " + version); +console.info('auth version = ' + version); ``` ### getAvailableStatus(deprecated) @@ -1194,9 +1186,9 @@ import userIAM_userAuth from '@ohos.userIAM.userAuth'; let auth = new userIAM_userAuth.UserAuth(); let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); + console.info('check auth support success'); } else { - console.error("check auth support fail, code = " + checkCode); + console.error('check auth support fail, code = ' + checkCode); } ``` @@ -1217,7 +1209,7 @@ auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLev | 参数名 | 类型 | 必填 | 说明 | | -------------- | ---------------------------------------- | ---- | ------------------------ | -| challenge | Uint8Array | 是 | 挑战值,可以填null。 | +| challenge | Uint8Array | 是 | 挑战值,可以传Uint8Array([])。 | | authType | [UserAuthType](#userauthtype8) | 是 | 认证类型,当前支持FACE。 | | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 认证信任等级。 | | callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | 是 | 回调函数。 | @@ -1234,20 +1226,21 @@ auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLev import userIAM_userAuth from '@ohos.userIAM.userAuth'; let auth = new userIAM_userAuth.UserAuth(); -auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // 此处添加认证成功逻辑 - } else { - // 此处添加认证失败逻辑 - } - } catch (e) { - console.info("auth onResult error = " + e); - } +let challenge = new Uint8Array([]); +auth.auth(challenge, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info('auth onResult result = ' + result); + console.info('auth onResult extraInfo = ' + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // 此处添加认证成功逻辑 + } else { + // 此处添加认证失败逻辑 + } + } catch (e) { + console.info('auth onResult error = ' + e); } + } }); ``` @@ -1286,9 +1279,9 @@ let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); let auth = new userIAM_userAuth.UserAuth(); let cancelCode = auth.cancelAuth(contextId); if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); + console.info('cancel auth success'); } else { - console.error("cancel auth fail"); + console.error('cancel auth fail'); } ``` @@ -1323,20 +1316,21 @@ onResult: (result : number, extraInfo : AuthResult) => void import userIAM_userAuth from '@ohos.userIAM.userAuth'; let auth = new userIAM_userAuth.UserAuth(); -auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // 此处添加认证成功逻辑 - } else { - // 此处添加认证失败逻辑 - } - } catch (e) { - console.info("auth onResult error = " + e); - } +let challenge = new Uint8Array([]); +auth.auth(challenge, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info('auth onResult result = ' + result); + console.info('auth onResult extraInfo = ' + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // 此处添加认证成功逻辑 + } else { + // 此处添加认证失败逻辑 + } + } catch (e) { + console.info('auth onResult error = ' + e); } + } }); ``` @@ -1365,16 +1359,30 @@ onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void import userIAM_userAuth from '@ohos.userIAM.userAuth'; let auth = new userIAM_userAuth.UserAuth(); -auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } +let challenge = new Uint8Array([]); +auth.auth(challenge, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info('auth onResult result = ' + result); + console.info('auth onResult extraInfo = ' + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // 此处添加认证成功逻辑 + } else { + // 此处添加认证失败逻辑 + } + } catch (e) { + console.info('auth onResult error = ' + e); } + }, + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info('auth onAcquireInfo module = ' + module); + console.info('auth onAcquireInfo acquire = ' + acquire); + console.info('auth onAcquireInfo extraInfo = ' + JSON.stringify(extraInfo)); + } catch (e) { + console.info('auth onAcquireInfo error = ' + e); + } + } }); ``` @@ -1497,6 +1505,8 @@ getAuthenticator(): Authenticator **示例:** ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + let authenticator = userIAM_userAuth.getAuthenticator(); ``` @@ -1537,13 +1547,15 @@ callback返回值: **示例:** ```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + let authenticator = userIAM_userAuth.getAuthenticator(); -authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ - if (code === userIAM_userAuth.ResultCode.SUCCESS) { - console.info("auth success"); - return; - } - console.error("auth fail, code = " + code); +authenticator.execute('FACE_ONLY', 'S2', (error, code)=>{ + if (code === userIAM_userAuth.ResultCode.SUCCESS) { + console.info('auth success'); + return; + } + console.error('auth fail, code = ' + code); }); ``` @@ -1577,11 +1589,13 @@ execute(type : AuthType, level : SecureLevel): Promise<number> **示例:** ```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + let authenticator = userIAM_userAuth.getAuthenticator(); -authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); +authenticator.execute('FACE_ONLY', 'S2').then((code)=>{ + console.info('auth success'); }).catch((error)=>{ - console.error("auth fail, code = " + error); + console.error('auth fail, code = ' + error); }); ``` diff --git a/zh-cn/application-dev/security/userauth-guidelines.md b/zh-cn/application-dev/security/userauth-guidelines.md index dc0d30c5490462517f12069f0f088ca23d232a51..c0d701f5d4f88901656ed3cb05e57b163a8dc380 100644 --- a/zh-cn/application-dev/security/userauth-guidelines.md +++ b/zh-cn/application-dev/security/userauth-guidelines.md @@ -33,6 +33,7 @@ userIAM_userAuth模块提供了用户认证的相关方法,包括查询认证 | ATL2 | FRR=10%时,FAR≤0.002%,7% { - return "ArkUI Web Component"; - }, - toString: () => { - console.info('Web Component toString'); - } - } + @State testObj: testClass = new testClass(); build() { Column() { @@ -70,7 +82,8 @@ try { this.webviewController.refresh(); } catch (error) { - console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + let e: business_error.BusinessError = error as business_error.BusinessError; + console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) Button('Register JavaScript To Window') @@ -78,7 +91,8 @@ try { this.webviewController.registerJavaScriptProxy(this.testObj, "objName", ["test", "toString"]); } catch (error) { - console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + let e: business_error.BusinessError = error as business_error.BusinessError; + console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) Web({ src: $rawfile('index.html'), controller: this.webviewController }) diff --git a/zh-cn/application-dev/web/web-open-in-new-window.md b/zh-cn/application-dev/web/web-open-in-new-window.md index b05a96ffeccbf763fb557dcb04f09ae60104de4e..faf0830039efd8b9e4190cacaafe60c431ad40c0 100644 --- a/zh-cn/application-dev/web/web-open-in-new-window.md +++ b/zh-cn/application-dev/web/web-open-in-new-window.md @@ -31,7 +31,7 @@ Web组件提供了在新窗口打开页面的能力,开发者可以通过[mult .multiWindowAccess(true) .onWindowNew((event) => { console.info("onWindowNew..."); - var popController: web_webview.WebviewController = new web_webview.WebviewController(); + let popController: web_webview.WebviewController = new web_webview.WebviewController(); // 开发者需要在此处新建窗口,跟popController关联,并且将popController返回给Web组件。如果不需要打开新窗口请将返回值设置为event.handler.setWebController(null); event.handler.setWebController(popController); }) diff --git a/zh-cn/application-dev/web/web-page-loading-with-web-components.md b/zh-cn/application-dev/web/web-page-loading-with-web-components.md index 46a1f5693b089de51201bd5457b4a8488698aedb..85f9873eaf9fd4afc8b1300ad98039aa18918360 100644 --- a/zh-cn/application-dev/web/web-page-loading-with-web-components.md +++ b/zh-cn/application-dev/web/web-page-loading-with-web-components.md @@ -19,6 +19,7 @@ ```ts // xxx.ets import web_webview from '@ohos.web.webview'; +import business_error from '@ohos.base'; @Entry @Component @@ -33,7 +34,8 @@ struct WebComponent { // 点击按钮时,通过loadUrl,跳转到www.example1.com this.webviewController.loadUrl('www.example1.com'); } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + let e: business_error.BusinessError = error as business_error.BusinessError; + console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) // 组件创建时,加载www.example.com @@ -64,6 +66,7 @@ struct WebComponent { ```ts // xxx.ets import web_webview from '@ohos.web.webview'; + import business_error from '@ohos.base'; @Entry @Component @@ -78,7 +81,8 @@ struct WebComponent { // 点击按钮时,通过loadUrl,跳转到local1.html this.webviewController.loadUrl($rawfile("local1.html")); } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + let e: business_error.BusinessError = error as business_error.BusinessError; + console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) // 组件创建时,通过$rawfile加载本地文件local.html @@ -111,6 +115,7 @@ Web组件可以通过[loadData()](../reference/apis/js-apis-webview.md#loaddata) ```ts // xxx.ets import web_webview from '@ohos.web.webview'; +import business_error from '@ohos.base'; @Entry @Component @@ -129,7 +134,8 @@ struct WebComponent { 'UTF-8' ); } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + let e: business_error.BusinessError = error as business_error.BusinessError; + console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) // 组件创建时,加载www.example.com diff --git a/zh-cn/application-dev/web/web-redirection-and-browsing-history-mgmt.md b/zh-cn/application-dev/web/web-redirection-and-browsing-history-mgmt.md index 4d64482bf4e2ed1751e2e1f120064d481fa670cf..2f0122560c1b2d4e4e211b2fc70ff7cd22161381 100644 --- a/zh-cn/application-dev/web/web-redirection-and-browsing-history-mgmt.md +++ b/zh-cn/application-dev/web/web-redirection-and-browsing-history-mgmt.md @@ -21,7 +21,6 @@ struct WebComponent { .onClick(() => { if (this.webviewController.accessBackward()) { this.webviewController.backward(); - return true; } }) Web({ src: 'https://www.example.com/cn/', controller: this.webviewController}) @@ -55,11 +54,13 @@ struct WebComponent { Column() { Web({ src: $rawfile('route.html'), controller: this.webviewController }) .onUrlLoadIntercept((event) => { - let url: string = event.data as string; - if (url.indexOf('native://') === 0) { - // 跳转其他界面 - router.pushUrl({ url:url.substring(9) }) - return true; + if (event) { + let url: string = event.data as string; + if (url.indexOf('native://') === 0) { + // 跳转其他界面 + router.pushUrl({ url:url.substring(9) }) + return true; + } } return false; }) @@ -122,18 +123,20 @@ Web组件可以实现点击前端页面超链接跳转到其他应用。 Column() { Web({ src: $rawfile('xxx.html'), controller: this.webviewController}) .onUrlLoadIntercept((event) => { - let url: string = event.data as string; - // 判断链接是否为拨号链接 - if (url.indexOf('tel://') === 0) { - // 跳转拨号界面 - call.makeCall(url.substring(6), (err) => { - if (!err) { - console.info('make call succeeded.'); - } else { - console.info('make call fail, err is:' + JSON.stringify(err)); - } - }); - return true; + if (event) { + let url: string = event.data as string; + // 判断链接是否为拨号链接 + if (url.indexOf('tel://') === 0) { + // 跳转拨号界面 + call.makeCall(url.substring(6), (err) => { + if (!err) { + console.info('make call succeeded.'); + } else { + console.info('make call fail, err is:' + JSON.stringify(err)); + } + }); + return true; + } } return false; }) diff --git a/zh-cn/application-dev/web/web-resource-interception-request-mgmt.md b/zh-cn/application-dev/web/web-resource-interception-request-mgmt.md index 6a01c946eaed3e56c21827337484bb105334390c..147f24b945b778f464182041f77374bf7bf3db46 100644 --- a/zh-cn/application-dev/web/web-resource-interception-request-mgmt.md +++ b/zh-cn/application-dev/web/web-resource-interception-request-mgmt.md @@ -51,10 +51,12 @@ Web网页上发起资源加载请求,应用层收到资源请求消息。应 Column() { Web({ src: $rawfile('example.html'), controller: this.controller }) .onInterceptRequest((event) => { - console.info('url:' + event.request.getRequestUrl()); - // 拦截页面请求 - if (event.request.getRequestUrl() !== 'https://www.intercept.com/test.html') { - return null; + if (event) { + console.info('url:' + event.request.getRequestUrl()); + // 拦截页面请求 + if (event.request.getRequestUrl() !== 'https://www.intercept.com/test.html') { + return this.responseResource; + } } // 构造响应数据 this.responseResource.setResponseData(this.webData); diff --git a/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md b/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md index 62abffed40b0d40ba7c093e1e03302e4cb963a69..d5673e31061c4f4eeb0e432a6f0494a687a2aabb 100644 --- a/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md +++ b/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md @@ -20,7 +20,7 @@ ## Ubuntu环境要求 -- Ubuntu18.04及以上版本,内存推荐16 GB及以上。 +- Ubuntu18.04及以上版本,X86_64架构,内存推荐16 GB及以上。 - Ubuntu系统的用户名不能包含中文字符。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.2/changelogs-bluetooth.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.10.1/changelogs-bluetooth.md similarity index 100% rename from zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.2/changelogs-bluetooth.md rename to zh-cn/release-notes/changelogs/OpenHarmony_4.0.10.1/changelogs-bluetooth.md