diff --git a/CODEOWNERS b/CODEOWNERS index 8110a344a6207d0b267e0bd7fd948fb22de01227..6d5fb7d29a8940cced64ac321d415bae9d2eda5c 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -199,9 +199,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 @@ -321,7 +321,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 @@ -334,7 +334,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 @@ -349,9 +349,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 @@ -374,7 +374,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 @@ -425,7 +425,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/application-models/figures/hop-cross-device-migration1.png b/en/application-dev/application-models/figures/hop-cross-device-migration1.png new file mode 100644 index 0000000000000000000000000000000000000000..5190b39b1fc311ca532e2127eb6e4dcad0d4c6f1 Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration1.png differ diff --git a/en/application-dev/application-models/figures/hop-cross-device-migration2.png b/en/application-dev/application-models/figures/hop-cross-device-migration2.png new file mode 100644 index 0000000000000000000000000000000000000000..a81cb2ab08506f4e368c6002be18d6931a056218 Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration2.png differ diff --git a/en/application-dev/application-models/figures/hop-cross-device-migration3.png b/en/application-dev/application-models/figures/hop-cross-device-migration3.png new file mode 100644 index 0000000000000000000000000000000000000000..86158bc2bcd54b83e8dc73aec204788aab0b95a3 Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration3.png differ diff --git a/en/application-dev/application-models/figures/hop-cross-device-migration4.png b/en/application-dev/application-models/figures/hop-cross-device-migration4.png new file mode 100644 index 0000000000000000000000000000000000000000..c743b3d10f8f1fa0a8be76cf10fff219c52d0ebf Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration4.png differ diff --git a/en/application-dev/application-models/figures/hop-cross-device-migration5.png b/en/application-dev/application-models/figures/hop-cross-device-migration5.png new file mode 100644 index 0000000000000000000000000000000000000000..9a166ef9b58b512696b8ca9efc95507eec25c72f Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration5.png differ diff --git a/en/application-dev/application-models/figures/hop-cross-device-migration6.png b/en/application-dev/application-models/figures/hop-cross-device-migration6.png new file mode 100644 index 0000000000000000000000000000000000000000..421a574fd18dca290e0b5ff5d1f0ff5814512d38 Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration6.png differ diff --git a/en/application-dev/application-models/figures/hop-cross-device-migration7.png b/en/application-dev/application-models/figures/hop-cross-device-migration7.png new file mode 100644 index 0000000000000000000000000000000000000000..5cc5cb2ca17b8bddf4776928f01c2bee63905cb2 Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration7.png differ diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md index b452d8ea493bbfe060094f13073b9bdd9eac4f65..54b3e8ecb1c3c2f035c577173f741d5989fad277 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -1,24 +1,18 @@ # Cross-Device Migration - ## When to Use -The main task of cross-device migration is to migrate the current mission (including the page component status) of an application to the target device so that the mission can continue on that device. Cross-device migration supports the following features: - -- Storage and restoration of custom data - -- Storage and restoration of page routing information and page component status data - -- Application compatibility detection - -- Setting the mission continuation state (**ACTIVE** by default) dynamically - - For example, for an editing application, only the text editing page needs to be migrated to the target service. In this case, you can call [setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) for precise control. +Cross-device migration is used to migrate the current mission (including the page component status) of an application to the target device so that the mission can continue on that device. Cross-device migration supports the following features: -- Determining whether to restore the page stack (page stack restored by default) +- Saving and restoring custom data +- Saving and restoring page routing information and page component status data +- Checking application compatibility +- Dynamically setting the mission continuation state (**ACTIVE** by default) - If an application wants to customize the page to be displayed after being migrated to the target device, the application can use [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams) for precise control. + For example, for an editing application, only the text editing page needs to be migrated to the target device. In this case, you can call [setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) for precise control. +- Determining whether to restore the page stack (restored by default) + If an application wants to customize the page to be displayed after being migrated to the target device, you can use [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams) for precise control. - Determining whether to exit the application on the initiator after a successful migration (application exit by default) You can use [SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams) for precise control. @@ -35,14 +29,9 @@ The following figure shows the cross-device migration process. ## Constraints -- Since cross-device migration mission management is not available, you can only develop applications that support cross-device migration. Your application cannot initiate migration. - -- Cross-device migration must be performed between the same UIAbility component. In other words, the components must have the same **bundleName**, **abilityName**, and **signature**. - - -## Best Practices - -For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB. +- The initiation of mission migration depends on system application control. You can implement the control capabilities by following the instructions provided in [Verification Guide](#verification-guide). +- Cross-device migration must be performed between the same UIAbility component. In other words, **bundleName**, **abilityName**, and **signature** of the component on the two devices must be the same. +- For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB. ## Available APIs @@ -53,24 +42,25 @@ The table below describes the main APIs used for cross-device migration. For det | **API**| Description| | -------- | -------- | -| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | Called by the initiator to store the data required for migration and indicate whether the migration is accepted.
- **AGREE**: The migration is accepted.
- **REJECT**: The migration is rejected, for example, when an application is abnormal in **onContinue()**.
- **MISMATCH**: The version does not match. The application on the initiator can obtain the version number of the target application from **onContinue()**. If the migration cannot be performed due to version mismatch, this error code is returned.| -| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page when the target uses cold start or the target is a multiton application and uses hot start. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| -| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page when the target is a singleton application and uses hot start. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| +| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | Called by the initiator to save the data required for migration and specify whether the migration is accepted.
- **AGREE**: The migration is accepted.
- **REJECT**: The migration is rejected. If the application is abnormal in **onContinue**, which results in abnormal display during data restoration, this error code is returned.
- **MISMATCH**: The version does not match. The application on the initiator can obtain the version of the target application from **onContinue**. If the migration cannot be performed due to version mismatch, this error code is returned.| +| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page if the target uses cold start or the target is a multiton application and uses hot start. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| +| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page if the target is a singleton application and uses hot start. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| ## How to Develop -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. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. -2. Display a dialog box to ask for 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). + For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). -3. Configure the fields related to cross-device migration in the configuration file. +2. Display a dialog box to ask for authorization from the user when the application is started for the first time. - Configure the application to support migration. + For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md##requesting-user-authorization). - Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device. +3. Configure the fields related to cross-device migration in the configuration file. + Configure the application to support migration. Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device. ```json { @@ -88,139 +78,273 @@ The table below describes the main APIs used for cross-device migration. For det Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). -4. Implement [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator. +4. Implement [onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator. + + [onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision-making. + +- Saving data to migrate: You can save the data to migrate in key-value pairs in **wantParam**. + +- Checking application compatibility: You can obtain the version of the target application from **wantParam.version** of the **onContinue** callback. Then you can check the compatibility between that version and the version of the current application. + +- Making a migration decision: You can determine migration is supported based on the return value of **onContinue**. For details about the return values, see [Available APIs](#available-apis). + + The sample code is as follows: + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + onContinue(wantParam : {[key: string]: Object}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) // Prepare data to migrate. + let continueInput = 'Data to migrate'; + // Save the data to migrate in the custom field (for example, data) of wantParam. + wantParam["data"] = continueInput + console.info(`onContinue input = ${wantParam["input"]}`); + return AbilityConstant.OnContinueResult.AGREE + } + ``` + +5. Restore data and load the UI. + + In the stage model, applications with different launch types can call different APIs to restore data and load the UI, as shown below. + + ![hop-cross-device-migration](figures/hop-cross-device-migration1.png) + + Implement **onCreate** and **onNewWant** in the UIAbility on the target device to implement data restoration. + +- Implementation example of **onCreate** + - The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate**. + - You can obtain the saved data from the **want** parameter. + - After data restoration is complete, call **restoreWindowStage** to trigger page restoration, including page stack information. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + export default class EntryAbility extends UIAbility { + storage : LocalStorage; + onCreate(want, launchParam) { + console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the data saved. + let continueInput = want.parameters.data + console.info(`continue input ${continueInput}`) + // Display the data on the current page. + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } + } + } + ``` +- For a singleton application, you must also implement **onNewWant**, in the same way as **onCreate**. + + Determine the migration scenario, restore data, and trigger page restoration in **onNewWant**. + + ```ts + export default class EntryAbility extends UIAbility { + storage : LocalStorage; + onNewWant(want, launchParam) { + console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the user data from the want parameter. + let continueInput = want.parameters.data + console.info(`continue input ${continueInput}`) + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } + } + } + ``` - [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision. - - Saving migrated data: You can save the data to be migrated in key-value pairs in **wantParam**. - - Checking application compatibility: You can obtain the version number of the target application from **wantParam** and that of the current application from **wantParam.version** of the **onContinue()** callback. Then you can check the compatibility between the two. - - Making a migration decision: You can determine whether to support the migration based on the return value of **onContinue()**. For details about the return values, see [Available APIs](#available-apis). +## Configuring Optional Migration Features + +### Dynamically Setting the Mission Continuation State + +Since API version 10, you can dynamically set the mission continuation state. Specifically, you can enable or disable mission migration as required by calling [setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10). By default, **ACTIVE** is set for an application that supports migration, indicating that mission continuation is enabled. + +| Value | Description | +| :------------------------------------- | ---------------------- | +| AbilityConstant.ContinueState.ACTIVE | Mission continuation is enabled for the application.| +| AbilityConstant.ContinueState.INACTIVE | Mission continuation is disabled for the application.| + +**Time for Setting the Mission Continuation State** + +The change of the mission migration state can be implemented based on service requirements. Typical methods are as follows: + +Call the API in the **onCreate** callback function of the UIAbility to set the mission continuation state when the application is created. + +```ts +// EntryAbility.ets +onCreate(want, launchParam) { + ... + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + ... +} +``` + +Call the API in the **onPageShow** callback function of the page to set the mission continuation state when a single page is displayed. + +```ts +// PageName.ets +struct PageName { + Build() { + ... + } + ... + onPageShow(){ + // When the page is displayed, set the mission continuation state to ACTIVE. + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + } +} +``` + +Set the mission continuation state in the event of a component. For example, set the state in the **onClick** event of the **Button** component. - The sample code is as follows: - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - - onContinue(wantParam : {[key: string]: any}) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - let workInput = AppStorage.Get('ContinueWork'); - // Set the user input data into wantParam. - wantParam["work"] = workInput // set user input data into want params - console.info(`onContinue input = ${wantParam["input"]}`); - return AbilityConstant.OnContinueResult.AGREE - } - ``` +```ts +// xxx.ets +Button(){ + ... +} +.onClick(()=>{ + // When the button is clicked, set the mission continuation state to ACTIVE. + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; +}) +``` -5. Implement **onCreate()** and **onNewWant()** in the UIAbility of the target application to implement data restoration. - - Implementation example of **onCreate** - - The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**. - - You can obtain the saved migration data from the **want** parameter. - - After data restoration is complete, call **restoreWindowStage** to trigger page restoration, including page stack information. - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - import distributedObject from '@ohos.data.distributedDataObject'; - - export default class EntryAbility extends UIAbility { - storage : LocalStorage; - onCreate(want, launchParam) { - console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // Obtain the user data from the want parameter. - let workInput = want.parameters.work - console.info(`work input ${workInput}`) - AppStorage.SetOrCreate('ContinueWork', workInput) - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - } - } - ``` - - For a singleton application, you must also implement **onNewWant()**, in the same way as **onCreate()**. - - Determine the migration scenario in **onNewWant()**, restore data, and trigger page restoration. - - ```ts - export default class EntryAbility extends UIAbility { - storage : LocalStorage; - onNewWant(want, launchParam) { - console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // Obtain the user data from the want parameter. - let workInput = want.parameters.work - console.info(`work input ${workInput}`) - AppStorage.SetOrCreate('ContinueWork', workInput) - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - } - } - ``` - -6. (Optional) Call [setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) to set the mission continuation state. +**Ensuring Mission Continuation Continuity** + +During UI page loading, the target application may have executed the command to set its own mission continuation state (for example, set the state to **INACTIVE** in **onCreate** during cold start or to **INACTIVE** during hot start since the peer has opened a page that cannot be migrated). To ensure a migration back to the initiator, you must set the mission continuation state to **ACTIVE** in **onCreate** and **onNewWant**. + +```ts +// EntryAbility.ets +onCreate(want, launchparam) { + ... + // Set the mission continuation state to ACTIVE when the launch is caused by continuation. This setting copes with cold start. + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + } +} + +onNewWant(want, launchparam) { + ... + // Set the mission continuation state to ACTIVE when the launch is caused by continuation. This setting copes with hot start. + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + } +} +``` + +### Migrating the Page Stack on Demand + +Configure whether to restore the page stack. By default, the page stack is restored. If an application does not want to use the page stack restored by the system, you can set the page to be displayed on the target device in **onWindowStageRestore**. For details about the configuration, see [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams). + +The index and second routes exist in the page stack of the initiator. However, the target application wants to display a specified page, rather than that of the initiator. + +Example: An application does not want automatically restored page stack information. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import wantConstant from '@ohos.app.ability.wantConstant'; + + onContinue(wantParam : {[key: string]: Object}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } + + onWindowStageRestore(windowStage) { + // Set the page to be displayed after the migration. + windowStage.setUIContent(this.contex, "pages/index", null); + } + ``` + +### Exiting the Application on Demand + +Configure whether to exit the application on the initiator after a successful migration. By default, the application on the initiator exits. If you do not want the application on the initiator to automatically exit after a successful migration, set the [SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams) parameter. + +Example: An application on the initiator does not exit after a successful migration. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import wantConstant from '@ohos.app.ability.wantConstant'; + + onContinue(wantParam : {[key: string]: Object}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } + ``` + +## Verification Guide + +A mission center demo is provided for you to verify the mission continuation capability of your application. The following walks you through on how to verify mission continuation by using the demo. + +### Compiling and Installing the Demo + +#### Environment Configuration + +[Switch to the full SDK](../faqs/full-sdk-switch-guide.md) on DevEco Studio. This is because the mission center uses the system API [@ohos.distributedDeviceManager](../reference/apis/js-apis-distributedDeviceManager.md), which is not provided in the public SDK. + +**NOTE**: The screenshots in this section are for reference only. The DevEco Studio and SDK versions in use prevail. + +#### Demo Download + +Download the mission center demo from [Sample Code](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/missionCenterDemo/dmsDemo/entry/src/main). + +#### Building Project Files + +1. Create an empty OpenHarmony project and replace the corresponding folders with the downloaded files. + +![hop-cross-device-migration](figures/hop-cross-device-migration2.png) + +2. Complete the signature, build, and installation. + + The default signature permission provided by the automatic signature template of DevEco Studio is normal. The mission center demo requires the **ohos.permission.MANAGE_MISSIONS** permission, which is at the system_core level. Therefore, you must escalate the permission to the system_core level. Specifically, change **"apl":"normal_core"** to **"apl":"system_core"** in the **UnsgnedReleasedProfileTemplate.json** file in **openharmony\*apiVersion*\toolchains\lib**. Then sign the files as follows: + + 1. Choose **File > Project Structure**. - For an application that supports migration, mission migration is enabled by default, and the system notifies peripheral trusted devices that a mission can be migrated or canceled based on the gain/loss focus state of the mission. If you want the system to send a notification to peripheral devices only when your application is in a specific scenario, set the migration continuation state to **INACTIVE** when the application is started and change it to **ACTIVE** when the application enters that specific scenario. + ![hop-cross-device-migration](figures/hop-cross-device-migration3.png) - - Example: An application does not require migration during startup. + 2. Click **Signing Configs** and click **OK**. - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + ![hop-cross-device-migration](figures/hop-cross-device-migration4.png) - onCreate(want, launchParam) { - this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { - console.info(`setMissionContinueState: ${JSON.stringify(result)}`); - }); - } - ``` - - Example: The application requires migration in a specific service process. + 3. Connect to the developer board and run the demo. - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +### Device Networking - this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { - console.info(`setMissionContinueState: ${JSON.stringify(result)}`); - }); - ``` +1. Open the calculators of devices A and B. -7. (Optional) Configure whether to restore the page stack. +2. Click the arrow in the upper right corner to select device B. - By default, the page stack is restored. If an application does not want to use the page stack restored by the system, you can set the page to be displayed in **onWindowStageRestore()**. For details about the configuration, see [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams). +3. Select a trusted device on device B. The PIN is displayed. - - Example: An application does not want automatically restored page stack information. +4. Enter the PIN on device A. - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import wantConstant from '@ohos.app.ability.wantConstant.d.ts'; +5. Verify the networking. Enter a number on device A. If the number is displayed on device B, the networking is successful. - onContinue(wantParam : {[key: string]: any}) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; - return AbilityConstant.OnContinueResult.AGREE; - } +### Initiation Migration - onWindowStageRestore(windowStage) { - // Set the page to be displayed after the migration. - windowStage.setUIContent(this.contex, "pages/index", null); - } - ``` +1. Open your application on device B, and open the mission center demo on device A. The name of device A (Local: OpenHarmony 3.2) and the name of device B (OpenHarmony 3.2) are displayed on device A. -8. (Optional) Configure whether to exit the application on the initiator after a successful migration. +![hop-cross-device-migration](figures/hop-cross-device-migration5.png) - By default, the application on the initiator exits. If you do not want the application on the initiator to automatically exit after a successful migration, set the [SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams) parameter. +2. Click the name of device B. The application of device B is displayed. - - Example: An application on the initiator does not exit after a successful migration. +![hop-cross-device-migration](figures/hop-cross-device-migration6.png) - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import wantConstant from '@ohos.app.ability.wantConstant.d.ts'; +3. Drag the application to the name of device A. The application on device A is started, and the application on device B exits. - onContinue(wantParam : {[key: string]: any}) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; - return AbilityConstant.OnContinueResult.AGREE; - } - ``` +![hop-cross-device-migration](figures/hop-cross-device-migration7.png) diff --git a/en/application-dev/application-models/hop-multi-device-collaboration.md b/en/application-dev/application-models/hop-multi-device-collaboration.md index b6e064d352ab2a0a7f61202f1ed04845569569a5..4153b2873bf88898b87604e1061294297c60117a 100644 --- a/en/application-dev/application-models/hop-multi-device-collaboration.md +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -1,4 +1,4 @@ -# Multi-device Collaboration (for System Applications Only) +# Multi-device Collaboration ## When to Use @@ -57,29 +57,31 @@ On device A, touch the **Start** button provided by the initiator application to 3. Obtain the device ID of the target device. ```ts - import deviceManager from '@ohos.distributedHardware.deviceManager'; + import deviceManager from '@ohos.distributedDeviceManager'; - let dmClass; + let dmClass: deviceManager.DeviceManager; function initDmClass() { // createDeviceManager is a system API. - deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => { - if (err) { - ... - return - } - dmClass = dm - }) + try{ + dmClass = deviceManager.createDeviceManager('ohos.samples.demo'); + } catch(err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } } function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass !== null) { - let list = dmClass.getTrustedDeviceListSync() + let list = dmClass.getAvailableDeviceListSync(); if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') { - console.info('EntryAbility onButtonClick getRemoteDeviceId err: list is null') + console.info('getRemoteDeviceId err: list is null'); + return; + } + if (list.length === 0) { + console.info("getRemoteDeviceId err: list is empty"); return; } - return list[0].deviceId + return list[0].networkId; } else { - console.info('EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null') + console.info('getRemoteDeviceId err: dmClass is null'); } } ``` @@ -90,8 +92,8 @@ On device A, touch the **Start** button provided by the initiator application to let want = { deviceId: getRemoteDeviceId(), bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. + abilityName: 'EntryAbility', + moduleName: 'entry', // moduleName is optional. } // context is the AbilityContext of the initiator UIAbility. this.context.startAbility(want).then(() => { @@ -217,7 +219,7 @@ A system application can connect to a service on another device by calling [conn 2. Display a dialog box to ask for 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. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available. +3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service-for-system-applications-only). Perform this operation only if no background service is available. 4. Connect to the background service. - Implement the **IAbilityConnection** class. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a service is connected, **onDisconnect()** is invoked when a service is unexpectedly disconnected, and **onFailed()** is invoked when the connection to a service fails. @@ -477,8 +479,8 @@ The following describes how to implement multi-device collaboration through cros ```ts const MSG_SEND_METHOD: string = 'CallSendMsg'; - originMsg: string = ''; - backMsg: string = ''; + let originMsg: string = ''; + let backMsg: string = ''; async onButtonCallWithResult(originMsg, backMsg) { try { let msg = new MyParcelable(1, originMsg); diff --git a/en/application-dev/application-models/inter-device-interaction-hop-overview.md b/en/application-dev/application-models/inter-device-interaction-hop-overview.md index 2f892b689fa93c680c37b3c27b641bc21bb6ffbb..3595a4ea0a1827307c04a955a1915247ba19817b 100644 --- a/en/application-dev/application-models/inter-device-interaction-hop-overview.md +++ b/en/application-dev/application-models/inter-device-interaction-hop-overview.md @@ -20,12 +20,15 @@ In OpenHarmony, distributed operations across devices are called continuation (a - **Multi-device collaboration** - Multi-device collaboration provides users with more efficient and immersive experience than with a single device. A typical multi-device collaboration scenario is as follows: You open the same note on devices A and B. On device A, you select images from the local Gallery, insert them to the note, and edit them. On device B, you edit the text. Another typical scenario is as follows: You are chatting with a customer on device A, and the customer asks for a file, which is stored on device B. You can use the chat software to open the file application on device B, select the required file, and send it back to device A. Then, you use the chat software to send it to the customer. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service. + Multi-device collaboration provides users with more efficient and immersive experience than with a single device. Multi-device collaboration is used in the following typical scenarios: + + - Scenario 1: You open the same note on devices A and B. On device A, you select images from the local Gallery, insert them to the note, and edit them. On device B, you edit the text. + - Scenario 2: : You are chatting with a customer on device A, and the customer asks for a file, which is stored on device B. You can use the chat software to open the file application on device B, select the required file, and send it back to device A. Then, you use the chat software to send it to the customer. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service. ## Continuation Architecture -OpenHarmony provides a set of APIs for you to implement continuation in your applications. The continuation architecture has the following advantages: +OpenHarmony provides APIs for you to implement continuation in your applications. The continuation architecture has the following advantages: - Capabilities such as remote service invocation to facilitate service design @@ -39,9 +42,9 @@ The following figure shows the continuation architecture. ![hop-structure](figures/hop-structure.png) -- Cross-device migration mission management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result. (This capability is unavailable yet.) +- Cross-device migration mission management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result. -- Multi-device collaboration mission management: The initiator accepts an application registration request and provides management capabilities such as starting or stopping collaboration and status display. (This capability is unavailable yet.) +- Multi-device collaboration mission management: The initiator accepts an application registration request and provides management capabilities such as starting or stopping collaboration and status display. - Distributed component management: provides capabilities such as remote service startup, remote service connection, and remote migration, and provides applications with cross-device migration or multi-device collaboration based on a combination of these capabilities. diff --git a/en/application-dev/application-models/lifecycleapp-switch.md b/en/application-dev/application-models/lifecycleapp-switch.md index ae18625ecee0d281e9bd37b806bba5ae69a385c2..118b1f44c7bddca04ef602f285414544e9aa134d 100644 --- a/en/application-dev/application-models/lifecycleapp-switch.md +++ b/en/application-dev/application-models/lifecycleapp-switch.md @@ -6,16 +6,16 @@ | onShow?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)
Listens for the switching to the [foreground](../reference/apis/js-apis-window.md#windowstageeventtype9).| | onHide?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)
Listens for the switching to the [background](../reference/apis/js-apis-window.md#windowstageeventtype9).| | onDestroy?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onDestroy(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityondestroy) | -| onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) | +| onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) | | onWindowDisplayModeChanged?(isShownInMultiWindow: boolean, newConfig: resourceManager.Configuration): void; | There is no corresponding API in the stage model.| No corresponding API is provided.| | onStartContinuation?(): boolean; | There is no corresponding API in the stage model.| In the stage model, an application does not need to detect whether the continuation is successful (detected when the application initiates the continuation request). Therefore, the **onStartContinuation()** callback is deprecated.| | onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: Object}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) | | onCompleteContinuation?(result: number): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | -| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)
In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.| +| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
[onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)
In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.| | onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | | onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) | -| onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
After an application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.| +| onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
After an application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.| | onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) | | onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) | -| onNewWant?(want: Want): void; | \@ohos.app.ability.UIAbility.d.ts | [onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) | +| onNewWant?(want: Want): void; | \@ohos.app.ability.UIAbility.d.ts | [onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) | | onMemoryLevel?(level: number): void | \@ohos.app.ability.UIAbility.d.ts | [onMemoryLevel(level: AbilityConstant.MemoryLevel): void;](../reference/apis/js-apis-app-ability-ability.md#abilityonmemorylevel) | diff --git a/en/application-dev/application-models/pageability-switch.md b/en/application-dev/application-models/pageability-switch.md index 23c663ca14a25bba25aef5c1693a519a1a0bff6c..1de52bc6b6fa6e744540baaa884ba559c3eaf350 100644 --- a/en/application-dev/application-models/pageability-switch.md +++ b/en/application-dev/application-models/pageability-switch.md @@ -8,30 +8,30 @@ The PageAbility component in the FA model corresponds to the UIAbility component 2. Migrate the PageAbility code to the UIAbility. + The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The table below describes the details. - - | PageAbility| UIAbility| Mapping Description| - | -------- | -------- | -------- | - | onCreate(): void| onCreate(want: Want, param: AbilityConstant.LaunchParam): void | The two methods have the same meaning and invoking time. In the stage model, parameters are added to the callback so that you can obtain startup-related data during creation.| - | NA | onWindowStageCreate(windowStage: window.WindowStage): void| This method is available only in the stage model. The callback is invoked when a window is created.| - | onActive(): void | on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;
WindowStageEventType.ACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| - | onShow(): void | onForeground(): void | The two methods have the same meaning, invoking time, and parameters.| - | onNewWant(want: Want): void| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void| The two methods have the same meaning and invoking time. In the stage model, the **LaunchParam** parameter is added to notify the application of the startup cause.| - | onInactive(): void| on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;
WindowStageEventType.INACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| - | onHide(): void | onBackground(): void | The two methods have the same meaning, invoking time, and parameters.| - | NA | onWindowStageDestroy(): void | This method is available only in the stage model. The callback is invoked when a window is destroyed.| + +| PageAbility| UIAbility| Mapping Description| +| -------- | -------- | -------- | +| onCreate(): void| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void | The two methods have the same meaning and invoking time. In the stage model, parameters are added to the callback so that you can obtain startup-related data during creation.| +| NA | onWindowStageCreate(windowStage: window.WindowStage): void| This method is available only in the stage model. The callback is invoked when a window is created.| +| onActive(): void | on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;
WindowStageEventType.ACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| +| onShow(): void | onForeground(): void | The two methods have the same meaning, invoking time, and parameters.| +| onNewWant(want: Want): void| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void | The two methods have the same meaning and invoking time. In the stage model, the **LaunchParam** parameter is added to notify the application of the startup cause.| +| onInactive(): void| on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;
WindowStageEventType.INACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| +| onHide(): void | onBackground(): void | The two methods have the same meaning, invoking time, and parameters.| +| NA | onWindowStageDestroy(): void | This method is available only in the stage model. The callback is invoked when a window is destroyed.| | onDestroy(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.| - + ![pageability-switch](figures/pageability-switch.png) - + 3. Adjust the migrated code, since the methods of loading pages are different. - In the FA model, you can configure the page to be loaded by setting page information in **config.json**. - In the stage model, call **windowStage.loadContent** in the **onWindowStageCreate** callback to load a page. For example, to load the **pages/Index** page after the ability is started, use the following code in the **config.json** file in the FA model: - - + ```json "pages" : [ "pages/Index" @@ -39,8 +39,7 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The ``` In the stage model, implement the following method in **MainAbility**: - - + ```ts import Window from '@ohos.window' @@ -53,4 +52,4 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The } }); } - ``` + ``` \ No newline at end of file diff --git a/en/application-dev/application-models/service-widget-overview.md b/en/application-dev/application-models/service-widget-overview.md index 528d9d4c134107c30de75f7f9e84ab42be514224..481f2c53f9a15b78655b7f6eaafd232378fe4469 100644 --- a/en/application-dev/application-models/service-widget-overview.md +++ b/en/application-dev/application-models/service-widget-overview.md @@ -1,7 +1,7 @@ # Service Widget Overview -A service widget (also called widget) is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. A widget usually appears as a part of the UI of another application (which currently can only be a system application, such as the home screen) and provides basic interactive features such as opening a UI page or sending a message. +A service widget (also called widget) is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. A widget is usually displayed as part of the UI of another application (which can only be a system application, such as the home screen) and provides basic interactive features such as opening a UI page or sending a message. ## Service Widget Architecture @@ -14,17 +14,17 @@ Before you get started, it would be helpful if you have a basic understanding of - Widget host: an application that displays the widget content and controls the widget location. An example is the home screen in the preceding figure. - - Application icon: an application entry icon, clicking which starts the application process. The icon content does not support interactions. - - Widget: an interactive UI in various sizes. It may provide buttons to implement different functions, such as the button to [update the widget content](arkts-ui-widget-event-formextensionability.md) or [switch to an application](arkts-ui-widget-event-router.md). + - Application icon: an icon for entry to an application, clicking which starts the application process. The icon content does not support interactions. + - Widget: an interactive UI in various sizes. It may provide buttons to implement different features, such as the button to [update the widget content](arkts-ui-widget-event-formextensionability.md) or [switch to an application](arkts-ui-widget-event-router.md). -- Card provider: an application that provides service widget content to be displayed. It controls the display content, display logic, and component click events triggered on a service widget. +- Widget provider: an application that provides widget content to be displayed. It controls the display content, display logic, and component click events triggered on a widget. - - FormExtensionAbility: widget service logic module, which provides lifecycle callbacks invoked when a widget is created, destroyed, or updated. - - Widget page: widget UI module, which contains display and interaction information such as components, layouts, and events. + - FormExtensionAbility: a widget service logic module, which provides lifecycle callbacks invoked when a widget is created, destroyed, or updated. + - Widget page: a widget UI module, which contains display and interaction information such as components, layouts, and events. -Below is the typical procedure of using the widget: +Below is the typical procedure of using a widget: -**Figure 2** Typical procedure of using the widget +**Figure 2** Typical procedure of using a widget ![WidgetUse](figures/WidgetUse.png) @@ -35,7 +35,7 @@ Below is the typical procedure of using the widget: 3. Touch the **Add to home** button. The widget is then added to the home screen. -## Widget UI Development Mode +## Widget UI Development Modes In the stage model, the UI of a widget can be developed in [ArkTS](arkts-ui-widget-working-principles.md) or [JS](js-ui-widget-development.md). @@ -45,7 +45,7 @@ In the stage model, the UI of a widget can be developed in [ArkTS](arkts-ui-widg ArkTS widgets and JS widgets have different implementation principles and features. The following table lists the differences in capabilities. -| Category| JS widget| ArkTS widget| +| Category| JS Widget| ArkTS Widget| | -------- | -------- | -------- | | Development paradigm| Web-like paradigm| Declarative paradigm| | Component capability| Supported| Supported| diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md index 56dd9198f291352413f72e3b2ada766c5c729e38..73dcb25754e00558130f535990589fc211583614 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -29,7 +29,7 @@ This scenario is possible when an application contains multiple UIAbility compon Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. To start FuncAbility from EntryAbility, proceed as follows: 1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) and pass the [want](../reference/apis/js-apis-app-ability-want.md) parameter to start the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module from EntryAbility; **parameters** is used to carry custom information. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). - + ```ts let context = ...; // UIAbilityContext let want = { @@ -48,12 +48,12 @@ Assume that your application has two UIAbility components: EntryAbility and Func console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` - + 2. In FuncAbility, use [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to receive the parameters passed in by EntryAbility. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - + export default class FuncAbility extends UIAbility { onCreate(want, launchParam) { // Receive the parameters passed by the initiator UIAbility. @@ -63,16 +63,16 @@ Assume that your application has two UIAbility components: EntryAbility and Func } } ``` - + > **NOTE** > > In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter. - + 3. To stop the **UIAbility** instance after the FuncAbility service is not needed, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility. - + ```ts let context = ...; // UIAbilityContext - + // context is the UIAbilityContext of the UIAbility instance to stop. context.terminateSelf((err) => { if (err.code) { @@ -81,11 +81,11 @@ Assume that your application has two UIAbility components: EntryAbility and Func } }); ``` - + > **NOTE** > > When [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called to stop the **UIAbility** instance, the snapshot of the instance is retained by default. That is, the mission corresponding to the instance is still displayed in Recents. If you do not want to retain the snapshot, set **removeMissionAfterTerminate** under the [abilities](../quick-start/module-configuration-file.md#abilities) tag to **true** in the [module.json5 file](../quick-start/module-configuration-file.md) of the corresponding UIAbility. - + 4. To stop all UIAbility instances of the application, call [killProcessBySelf()](../reference/apis/js-apis-inner-application-applicationContext.md#applicationcontextkillallprocesses9) of [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md). @@ -94,7 +94,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func When starting FuncAbility from EntryAbility, you may want the result to be returned after the FuncAbility service is finished. For example, after the sign-in operation is finished in the sign-in UIAbility of your application, you want the sign-in result to be returned to the entry UIAbility. 1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). - + ```ts let context = ...; // UIAbilityContext let want = { @@ -113,9 +113,9 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` - + 2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. - + ```ts let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; @@ -138,15 +138,15 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur } }); ``` - + 3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as that specified in the preceding step. - + ```ts let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; - + ... - + // context is the UIAbilityContext of the initiator UIAbility. context.startAbilityForResult(want).then((data) => { if (data?.resultCode === RESULT_CODE) { @@ -173,7 +173,7 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview The following example describes how to start the UIAbility of another application through implicit Want. 1. Install multiple document applications on your device. In the [module.json5 file](../quick-start/module-configuration-file.md) of each UIAbility component, configure **entities** and **actions** under **skills**. - + ```json { "module": { @@ -199,7 +199,7 @@ The following example describes how to start the UIAbility of another applicatio ``` 2. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system identifies the UIAbility instances that match the **entities** and **actions** information, a dialog box is displayed, showing the list of matching UIAbility instances for users to select. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). - + ```ts let context = ...; // UIAbilityContext let want = { @@ -210,7 +210,7 @@ The following example describes how to start the UIAbility of another applicatio // entities can be omitted. entities: ['entity.system.default'], } - + // context is the UIAbilityContext of the initiator UIAbility. context.startAbility(want).then(() => { console.info('Succeeded in starting ability.'); @@ -218,16 +218,16 @@ The following example describes how to start the UIAbility of another applicatio console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` - + The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select the application to use. ![](figures/uiability-intra-device-interaction.png) 3. To stop the **UIAbility** instance when the document application is not in use, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). - + ```ts let context = ...; // UIAbilityContext - + // context is the UIAbilityContext of the UIAbility instance to stop. context.terminateSelf((err) => { if (err.code) { @@ -243,7 +243,7 @@ The following example describes how to start the UIAbility of another applicatio If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). An example scenario is that your application needs to start a third-party payment application and obtain the payment result. 1. In the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility corresponding to the payment application, set **entities** and **actions** under **skills**. - + ```json { "module": { @@ -269,7 +269,7 @@ If you want to obtain the return result when using implicit Want to start the UI ``` 2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start the UIAbility of the payment application. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the initiator UIAbility after the payment UIAbility stops itself. After the system identifies the UIAbility instances that match the **entities** and **actions** information, a dialog box is displayed, showing the list of matching UIAbility instances for users to select. - + ```ts let context = ...; // UIAbilityContext let want = { @@ -280,7 +280,7 @@ If you want to obtain the return result when using implicit Want to start the UI // entities can be omitted. entities: ['entity.system.default'] } - + // context is the UIAbilityContext of the initiator UIAbility. context.startAbilityForResult(want).then((data) => { ... @@ -288,9 +288,9 @@ If you want to obtain the return result when using implicit Want to start the UI console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` - + 3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter. - + ```ts let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; @@ -313,17 +313,17 @@ If you want to obtain the return result when using implicit Want to start the UI } }); ``` - + 4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). - + ```ts let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; - + let want = { // Want parameter information. }; - + // context is the UIAbilityContext of the initiator UIAbility. context.startAbilityForResult(want).then((data) => { if (data?.resultCode === RESULT_CODE) { @@ -350,8 +350,8 @@ The window mode is specified by the **windowMode** field in the [StartOptions](. > **NOTE** > -> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode. -> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field under [abilities](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. +> - If the **windowMode** field is not specified, the UIAbility is started in the default window mode. +> - To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field under [abilities](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. The following describes how to start the FuncAbility from the EntryAbility page and display it in floating window mode. @@ -472,7 +472,7 @@ U->>S: Open the SMS app. S-->>U: The home page of the SMS app is displayed. U->>S: Return to the home screen. S->>S: The SMS app enters the background. -U->>C: Open the Contacts app. +U->>C: Open the Contacts app. C-->>U: The page of the Contact app is displayed. U->>C: Touch the SMS button next to a contact. C->>S: Start the SMS app with Want. @@ -488,19 +488,19 @@ The development procedure is as follows: import UIAbility from '@ohos.app.ability.UIAbility'; import Want from '@ohos.app.ability.Want'; import window from '@ohos.window'; - + import { Router, UIContext } from '@ohos.arkui.UIContext'; - + export default class EntryAbility extends UIAbility { funcAbilityWant: Want; uiContext: UIContext; - + ... - + onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created. Set a main page for this UIAbility. ... - + let windowClass: window.Window; windowStage.getMainWindow((err, data) => { if (err.code) { @@ -520,8 +520,8 @@ The development procedure is as follows: export default class EntryAbility extends UIAbility { funcAbilityWant: Want; uiContext: UIContext; - - onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam) { + + onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { if (want?.parameters?.router && want.parameters.router === 'funcA') { let funcAUrl = 'pages/Second'; let router: Router = this.uiContext.getRouter(); @@ -532,7 +532,7 @@ The development procedure is as follows: }) } } - + ... } ``` @@ -580,9 +580,9 @@ The following figure shows the call process. > **NOTE** > - Currently, only system applications can use the call. -> +> > - The launch type of the CalleeAbility must be **singleton**. -> +> > - Both local (intra-device) and cross-device calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device call, see [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call). @@ -614,24 +614,24 @@ The implementation of using the call for UIAbility interaction involves two part For the CalleeAbility, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. 1. Configure the launch type of the CalleeAbility. - + For example, set the launch type of the CalleeAbility to **singleton**. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). - + 2. Import the **UIAbility** module. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; ``` 3. Define the agreed parcelable data. - The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string. + The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string. + ```ts export default class MyParcelable { num: number = 0; str: string = ''; - constructor(num, string) { this.num = num; this.str = string; @@ -650,9 +650,9 @@ For the CalleeAbility, implement the callback to receive data and the methods to } } ``` - -4. Implement **Callee.on** and **Callee.off**. +4. Implement **Callee.on** and **Callee.off**. + The time to register a listener for the CalleeAbility depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the UIAbility and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: @@ -696,7 +696,7 @@ For the CalleeAbility, implement the callback to receive data and the methods to ### Accessing the CalleeAbility 1. Import the **UIAbility** module. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; ``` @@ -735,4 +735,4 @@ For the CalleeAbility, implement the callback to receive data and the methods to console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`); } } - ``` + ``` \ No newline at end of file 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/media/audio-playback-overview.md b/en/application-dev/media/audio-playback-overview.md index 767f3dd775546f58844885406bc4816dc82a2eb6..0c872d383ac7a4745a3f270cc93ac466ee0a198a 100644 --- a/en/application-dev/media/audio-playback-overview.md +++ b/en/application-dev/media/audio-playback-overview.md @@ -8,9 +8,11 @@ OpenHarmony provides multiple classes for you to develop audio playback applicat - [AudioRenderer](using-audiorenderer-for-playback.md): provides ArkTS and JS API to implement audio output. It supports only the PCM format and requires applications to continuously write audio data. The applications can perform data preprocessing, for example, setting the sampling rate and bit width of audio files, before audio input. This class can be used to develop more professional and diverse playback applications. To use this class, you must have basic audio processing knowledge. -- [OpenSL ES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio output in PCM format and is applicable to playback applications that are ported from other embedded platforms or that implements audio output at the native layer. +- [OpenSL ES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform native audio APIs. It supports audio output in PCM format and is suitable for playback applications that are ported from other embedded platforms or that implement audio output at the native layer. -- [TonePlayer](using-toneplayer-for-playback.md): provides ArkTS and JS API to implement the playback of dialing tones and ringback tones. It can be used to play the content selected from a fixed type range, without requiring the input of media assets or audio data. This class is application to specific scenarios where dialing tones and ringback tones are played. is available only to system applications. +- [Using OHAudio for Audio Playback](using-ohaudio-for-playback.md): provides a set of native APIs for audio output. These APIs are normalized in design and support both common and low-latency audio channels. They are suitable for playback applications that implement audio output at the native layer. + +- [TonePlayer](using-toneplayer-for-playback.md): provides ArkTS and JS APIs to implement the playback of dialing tones and ringback tones. It can be used to play the content selected from a fixed type range, without requiring the input of media assets or audio data. This class is applicable to specific scenarios where dialing tones and ringback tones are played. It is available only to system applications. - Applications often need to use short sound effects, such as camera shutter sound effect, key press sound effect, and game shooting sound effect. Currently, only the **AVPlayer** class can implement audio file playback. More APIs will be provided to support this scenario in later versions. diff --git a/en/application-dev/media/audio-recording-overview.md b/en/application-dev/media/audio-recording-overview.md index 2c6fb6fe5b8ffd0e82478d450e64bfc0e10257c6..39eefc124320c7474dba048396cb0363d1bc8511 100644 --- a/en/application-dev/media/audio-recording-overview.md +++ b/en/application-dev/media/audio-recording-overview.md @@ -8,7 +8,9 @@ OpenHarmony provides multiple classes for you to develop audio recording applica - [AudioCapturer](using-audiocapturer-for-recording.md): provides ArkTS and JS API to implement audio input. It supports only the PCM format and requires applications to continuously read audio data. The application can perform data processing after audio output. This class can be used to develop more professional and diverse recording applications. To use this class, you must have basic audio processing knowledge. -- [OpenSL ES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio input in PCM format and is applicable to recording applications that are ported from other embedded platforms or that implements audio input at the native layer. +- [OpenSL ES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform native audio APIs. It supports audio input in PCM format and is suitable for recording applications that are ported from other embedded platforms or that implement audio input at the native layer. + +- [Using OHAudio for Audio Recording](using-ohaudio-for-recording.md): provides a set of native APIs for audio input. These APIs are normalized in design and support both common and low-latency audio channels. They are suitable for playback applications that implement audio input at the native layer. ## Precautions for Developing Audio Recording Applications diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index a0990b276e19ef44bbf2f93d76f51a90552fe374..c55b62ffd047ff92b3949dc9c3a9e62e8c608f1d 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -241,7 +241,7 @@ The **abilities** tag represents the UIAbility configuration of the module, whic | label | Name of the UIAbility component displayed to users. The value is a string resource index.| String| Yes (initial value: left empty)
If **UIAbility** is set to **MainElement**, this attribute is mandatory.| | permissions | Permissions required for another application to access the UIAbility component.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of predefined permission names.| String array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata information of the UIAbility component.| Object array| Yes (initial value: left empty)| -| exported | Whether the UIAbility component can be called by other applications.
- **true**: The UIAbility component can be called by other applications.
- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| +| exported | Whether the UIAbility component can be called by other applications.
- **true**: The UIAbility component can be called by other applications.
- **false**: The ExtensionAbility component cannot be called by other applications, not even by aa commands.| Boolean| Yes (initial value: **false**)| | continuable | Whether the UIAbility component can be [migrated](../application-models/hop-cross-device-migration.md).
- **true**: The UIAbility component can be migrated.
- **false**: The UIAbility component cannot be migrated.| Boolean| Yes (initial value: **false**)| | [skills](#skills) | Feature set of [wants](../application-models/want-overview.md) that can be received by the current UIAbility or ExtensionAbility component.
Configuration rules:
- For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an OpenHarmony application. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.)
- For HAPs of the feature type, you can configure **skills** attributes with the entry capability for an OpenHarmony application, but not for an OpenHarmony service.| Object array| Yes (initial value: left empty)| | backgroundModes | Continuous tasks of the UIAbility component.
Continuous tasks are classified into the following types:
- **dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.
- **audioPlayback**: audio playback service.
- **audioRecording**: audio recording service.
- **location**: location and navigation services.
- **bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables).
- **multiDeviceConnection**: multi-device interconnection service.
- **wifiInteraction**: Wi-Fi scanning, connection, and transmission services (as used in the Multi-screen Collaboration and clone features)
- **voip**: voice/video call and VoIP services.
- **taskKeeping**: computing service.| String array| Yes (initial value: left empty)| @@ -382,7 +382,7 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie | uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| |skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| -| exported | Whether the ExtensionAbility component can be called by other applications.
- **true**: The ExtensionAbility component can be called by other applications.
- **false**: The ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| +| exported | Whether the ExtensionAbility component can be called by other applications.
- **true**: The ExtensionAbility component can be called by other applications.
- **false**: The ExtensionAbility component cannot be called by other applications, not even by aa commands.| Boolean| Yes (initial value: **false**)| Example of the **extensionAbilities** structure: diff --git a/en/application-dev/quick-start/module-structure.md b/en/application-dev/quick-start/module-structure.md index 1d6cc3f873ef2929fb621a10dfdb5c40d5f3b16f..8ccbc87fff9e675285096fcb8e536b7aabb71b95 100644 --- a/en/application-dev/quick-start/module-structure.md +++ b/en/application-dev/quick-start/module-structure.md @@ -97,7 +97,7 @@ Example of the **module** tag structure: | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | -| moduleName | Name of the HAP file. The maximum length is 31 bytes. During application upgrade, this name can be changed. If it is changed, migration of module-related directories is required for the application. You can use the [file operation API](../reference/apis/js-apis-file-fs.md#fscopydir10) for migration.| String| No| +| moduleName | Name of the HAP file. The maximum length is 31 bytes. This name can be changed during application update. However, if it is changed, you need to adapt the application to the migration of module-related directories. You can use the [file operation API](../reference/apis/js-apis-file-fs.md#fscopydir10) for this purpose.| String| No| | moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No| | installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| | deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| @@ -203,7 +203,7 @@ Example of the metadata attribute: | label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
**NOTE**
The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| | uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)| | launchType | Launch type of the ability. The value can be **standard** or **singleton**.
**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)| -| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)| +| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications, not even by aa commands.| Boolean| Yes (initial value: **false**)| | permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)| |skills | Types of the **want** that can be accepted by the ability.| Object array| Yes (initial value: left empty)| | deviceCapability | Device capabilities required to run the ability. The value is an array of up to 512 elements, each of which contains a maximum of 64 bytes.| String array| Yes (initial value: left empty)| diff --git a/en/application-dev/quick-start/multi-hap-release-deployment.md b/en/application-dev/quick-start/multi-hap-release-deployment.md index 4d3d1167e7765e25f3e07942a0ce703e7e2b2355..01b38fdbb86016a8cfeeaa5e2452a28db260920c 100644 --- a/en/application-dev/quick-start/multi-hap-release-deployment.md +++ b/en/application-dev/quick-start/multi-hap-release-deployment.md @@ -57,7 +57,7 @@ You can debug HAP files using the methods: When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files. ## Deployment -The application market on the cloud distributes the applications to application market clients. These applications can contain one or more HAP files. After the user selects an application to download, the application market downloads all the HAP files contained in this application. +The application market on the cloud distributes the applications to application market clients. These applications can contain one or more HAP files. After the user selects an application to download, the application market downloads all the HAP files contained in this application whose **deliveryWithInstall** field is set to **true**. ## Installation on a Device After the download is complete, the application market client calls the installation API of the bundle manager service in the system to install the downloaded HAP files. The bundle manager service deploys HAP files by application in the specified directory to complete the application installation. diff --git a/en/application-dev/quick-start/start-overview.md b/en/application-dev/quick-start/start-overview.md index df1178706cc93fac75f9f443dcff2627b026b9c8..648b34458ba4ce74a07556a26dc6da957b0c5ed4 100644 --- a/en/application-dev/quick-start/start-overview.md +++ b/en/application-dev/quick-start/start-overview.md @@ -35,7 +35,7 @@ Along its evolution, OpenHarmony has provided two application models: For details about the differences between the FA model and stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). -To help you better understand the preceding basic concepts and application development process, **Getting Started** provides a development example that contains two pages in different programming languages and application models. +To help you better understand the preceding basic concepts and application development process, **Getting Started** walks you through an example of building the first ArkTS application with two pages in the stage model. ## Tool Preparation diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index f110588a54b0fca30f9e4ce2edb65d492aecbeea..e85577a76dda10afda7718d7ada062098173fa57 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -280,7 +280,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-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index 41f32713e0de5e611cec98753f439c345b3cbbe1..0f8e0049e83665f3e8f837dbff3ac64858024c6d 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -6,8 +6,8 @@ UIAbility is an application component that has the UI. The **UIAbility** module - [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). > **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 of this module can be used only in the stage model. ## Modules to Import @@ -29,7 +29,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ## UIAbility.onCreate -onCreate(want: Want, param: AbilityConstant.LaunchParam): void; +onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; Called to initialize the service logic when a UIAbility is created. @@ -46,7 +46,7 @@ Called to initialize the service logic when a UIAbility is created. ```ts class MyUIAbility extends UIAbility { - onCreate(want, param) { + onCreate(want, launchParam) { console.log('onCreate, want: ${want.abilityName}'); } } @@ -68,7 +68,7 @@ Called when a **WindowStage** is created for this UIAbility. | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** - + ```ts class MyUIAbility extends UIAbility { onWindowStageCreate(windowStage) { @@ -87,7 +87,7 @@ Called when the **WindowStage** is destroyed for this UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** - + ```ts class MyUIAbility extends UIAbility { onWindowStageDestroy() { @@ -112,7 +112,7 @@ Called when the **WindowStage** is restored during the migration of this UIAbili | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** - + ```ts class MyUIAbility extends UIAbility { onWindowStageRestore(windowStage) { @@ -131,7 +131,7 @@ Called when this UIAbility is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** - + ```ts class MyUIAbility extends UIAbility { @@ -161,7 +161,7 @@ Called when this UIAbility is switched from the background to the foreground. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** - + ```ts class MyUIAbility extends UIAbility { onForeground() { @@ -180,7 +180,7 @@ Called when this UIAbility is switched from the foreground to the background. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** - + ```ts class MyUIAbility extends UIAbility { onBackground() { @@ -211,7 +211,7 @@ Called to save data during the ability migration preparation process. | [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.| **Example** - + ```ts import AbilityConstant from '@ohos.app.ability.AbilityConstant'; class MyUIAbility extends UIAbility { @@ -226,7 +226,7 @@ Called to save data during the ability migration preparation process. ## UIAbility.onNewWant -onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; +onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; Called when a new Want is passed in and this UIAbility is started again. @@ -237,15 +237,15 @@ Called when a new Want is passed in and this UIAbility is started again. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| -| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| +| launchParam | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| **Example** - + ```ts class MyUIAbility extends UIAbility { - onNewWant(want, launchParams) { + onNewWant(want, launchParam) { console.log('onNewWant, want: ${want.abilityName}'); - console.log('onNewWant, launchParams: ${JSON.stringify(launchParams)}'); + console.log('onNewWant, launchParam: ${JSON.stringify(launchParam)}'); } } ``` @@ -265,7 +265,7 @@ Dumps client information. | params | Array\ | Yes| Parameters in the form of a command.| **Example** - + ```ts class MyUIAbility extends UIAbility { onDump(params) { @@ -315,7 +315,7 @@ class MyUIAbility extends UIAbility { onShare(wantParam:{ [key: string]: Object }): void; -Called by this UIAbility to set data to share. **ohos.extra.param.key.shareUrl** indicates the online address of the service. +Called by this UIAbility to set data to share in the cross-device sharing scenario. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -323,10 +323,10 @@ Called by this UIAbility to set data to share. **ohos.extra.param.key.shareUrl** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wantParam | {[key: string]: Object} | Yes| **want** parameter.| +| wantParam | {[key: string]: Object} | Yes| Data to share.| **Example** - + ```ts import AbilityConstant from '@ohos.app.ability.AbilityConstant'; class MyUIAbility extends UIAbility { @@ -419,7 +419,7 @@ Sends sequenceable data to the target ability. For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - + ```ts class MyMessageAble{ // Custom parcelable data structure. name:'' @@ -569,7 +569,7 @@ Releases the caller interface of the target ability. For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - + ```ts let caller; export default class MainUIAbility extends UIAbility { @@ -615,7 +615,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| **Example** - + ```ts let caller; export default class MainUIAbility extends UIAbility { @@ -663,7 +663,7 @@ Registers a callback that is invoked when the remote ability state changes in th For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; @@ -717,7 +717,7 @@ Registers a callback that is invoked when the stub on the target ability is disc For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - + ```ts let caller; export default class MainUIAbility extends UIAbility { @@ -764,7 +764,7 @@ Deregisters a callback that is invoked when the stub on the target ability is di | 401 | If the input parameter is not valid parameter. | **Example** - + ```ts let caller; export default class MainUIAbility extends UIAbility { @@ -806,7 +806,7 @@ Deregisters a callback that is invoked when the stub on the target ability is di | type | string | Yes| Event type. The value is fixed at **release**.| **Example** - + ```ts let caller; export default class MainUIAbility extends UIAbility { @@ -823,7 +823,7 @@ Deregisters a callback that is invoked when the stub on the target ability is di }; caller.on('release', onReleaseCallBack); caller.off('release'); - } catch (error) { + } catch (error) { console.error('Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}'); } }).catch((err) => { @@ -929,7 +929,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** - + ```ts let method = 'call_Function'; export default class MainUIAbility extends UIAbility { 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-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 5da2213e83ae6d18cfe66227e12a143d8fe7a815..798e3124d610801e40e93722a02c5c1137c1a09d 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -672,7 +672,7 @@ Describes audio renderer information. | ------------- | --------------------------- | ---- | ---------------- | | content | [ContentType](#contenttype) | No | Audio content type.
This parameter is mandatory in API versions 8 and 9 and optional since API version 10.| | usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.| -| rendererFlags | number | Yes | Audio renderer flags.| +| rendererFlags | number | Yes | Audio renderer flags.
The value **0** means a common audio renderer, and **1** means a low-latency audio renderer. Currently, the JS APIs do not support the low-latency audio renderer.| ## InterruptResult9+ @@ -4341,9 +4341,9 @@ async function selectOutputDeviceByFilter(){ } ``` -### getPreferOutputDeviceForRendererInfo10+ +### getPreferredOutputDeviceForRendererInfo10+ -getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void +getPreferredOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void Obtains the output device with the highest priority based on the audio renderer information. This API uses an asynchronous callback to return the result. @@ -4356,6 +4356,15 @@ Obtains the output device with the highest priority based on the audio renderer | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. | | callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the information about the output device with the highest priority.| +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. Return by callback. | +| 6800301 | System error. Return by callback. | + **Example** ```js let rendererInfo = { @@ -4363,8 +4372,8 @@ let rendererInfo = { usage : audio.StreamUsage.STREAM_USAGE_MEDIA, rendererFlags : 0 } -async function getPreferOutputDevice() { - audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo, (err, desc) => { +async function getPreferredOutputDevice() { + audioRoutingManager.getPreferredOutputDeviceForRendererInfo(rendererInfo, (err, desc) => { if (err) { console.error(`Result ERROR: ${err}`); } else { @@ -4374,8 +4383,8 @@ async function getPreferOutputDevice() { } ``` -### getPreferOutputDeviceForRendererInfo10+ -getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise<AudioDeviceDescriptors> +### getPreferredOutputDeviceForRendererInfo10+ +getPreferredOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise<AudioDeviceDescriptors> Obtains the output device with the highest priority based on the audio renderer information. This API uses a promise to return the result. @@ -4399,7 +4408,8 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco | ID| Error Message| | ------- | --------------------------------------------| -| 6800101 | if input parameter value error | +| 6800101 | if input parameter value error. Return by promise. | +| 6800301 | System error. Return by promise. | **Example** @@ -4409,8 +4419,8 @@ let rendererInfo = { usage : audio.StreamUsage.STREAM_USAGE_MEDIA, rendererFlags : 0 } -async function getPreferOutputDevice() { - audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo).then((desc) => { +async function getPreferredOutputDevice() { + audioRoutingManager.getPreferredOutputDeviceForRendererInfo(rendererInfo).then((desc) => { console.info(`device descriptor: ${desc}`); }).catch((err) => { console.error(`Result ERROR: ${err}`); @@ -4418,9 +4428,9 @@ async function getPreferOutputDevice() { } ``` -### on('preferOutputDeviceChangeForRendererInfo')10+ +### on('preferredOutputDeviceChangeForRendererInfo')10+ -on(type: 'preferOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererInfo, callback: Callback): void +on(type: 'preferredOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererInfo, callback: Callback): void Subscribes to the change of the output device with the highest priority. This API uses an asynchronous callback to return the result. @@ -4430,7 +4440,7 @@ Subscribes to the change of the output device with the highest priority. This AP | Name | Type | Mandatory| Description | | :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Event type. The value **'preferOutputDeviceChangeForRendererInfo'** means the event triggered when the output device with the highest priority changes.| +| type | string | Yes | Event type. The value **'preferredOutputDeviceChangeForRendererInfo'** means the output device change event, which is triggered when the output device with the highest priority is changed.| | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. | | callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the output device with the highest priority. | @@ -4450,14 +4460,14 @@ let rendererInfo = { usage : audio.StreamUsage.STREAM_USAGE_MEDIA, rendererFlags : 0 } -audioRoutingManager.on('preferOutputDeviceChangeForRendererInfo', rendererInfo, (desc) => { +audioRoutingManager.on('preferredOutputDeviceChangeForRendererInfo', rendererInfo, (desc) => { console.info(`device descriptor: ${desc}`); }); ``` -### off('preferOutputDeviceChangeForRendererInfo')10+ +### off('preferredOutputDeviceChangeForRendererInfo')10+ -off(type: 'preferOutputDeviceChangeForRendererInfo', callback?: Callback): void +off(type: 'preferredOutputDeviceChangeForRendererInfo', callback?: Callback): void Unsubscribes from the change of the output device with the highest priority. @@ -4467,7 +4477,7 @@ Unsubscribes from the change of the output device with the highest priority. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value **'preferOutputDeviceChangeForRendererInfo'** means the event triggered when the output device with the highest priority changes.| +| type | string | Yes | Event type. The value **'preferredOutputDeviceChangeForRendererInfo'** means the output device change event, which is triggered when the output device with the highest priority is changed.| | callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used for unsubscription. | **Error codes** @@ -4481,7 +4491,157 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco **Example** ```js -audioRoutingManager.off('preferOutputDeviceChangeForRendererInfo'); +audioRoutingManager.off('preferredOutputDeviceChangeForRendererInfo'); +``` + +### getPreferredInputDeviceForCapturerInfo10+ + +getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void + +Obtains the input device with the highest priority based on the audio renderer information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the information about the input device with the highest priority.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | +| 6800301 | System error | + +**Example** +```js +let capturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 +} + +audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo, (err, desc) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info(`device descriptor: ${desc}`); + } +}); +``` + +### getPreferredInputDeviceForCapturerInfo10+ + +getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo): Promise<AudioDeviceDescriptors> + +Obtains the input device with the highest priority based on the audio renderer information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. | + +**Return value** + +| Type | Description | +| --------------------- | --------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the information about the input device with the highest priority.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | +| 6800301 | System error | + +**Example** + +```js +let capturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 +} + +audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo).then((desc) => { + console.info(`device descriptor: ${desc}`); +}).catch((err) => { + console.error(`Result ERROR: ${err}`); +}) +``` + +### on('preferredInputDeviceChangeForCapturerInfo')10+ + +on(type: 'preferredInputDeviceChangeForCapturerInfo', capturerInfo: AudioCapturerInfo, callback: Callback): void + +Subscribes to the change of the input device with the highest priority. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **'preferredInputDeviceChangeForCapturerInfo'** means the input device change event, which is triggered when the input device with the highest priority is changed.| +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. | +| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the input device with the highest priority. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | + +**Example** + +```js +let capturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 +} + +audioRoutingManager.on('preferredInputDeviceChangeForCapturerInfo', capturerInfo, (desc) => { + console.info(`device descriptor: ${desc}`); +}); +``` + +### off('preferredInputDeviceChangeForCapturerInfo')10+ + +off(type: 'preferredInputDeviceChangeForCapturerInfo', callback?: Callback): void + +Unsubscribes from the change of the input device with the highest priority. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **'preferredInputDeviceChangeForCapturerInfo'** means the input device change event, which is triggered when the input device with the highest priority is changed.| +| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used for unsubscription. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | + +**Example** + +```js +audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo'); ``` ## AudioRendererChangeInfoArray9+ @@ -4861,6 +5021,14 @@ Sets an audio effect mode. This API uses an asynchronous callback to return the | mode | [AudioEffectMode](#audioeffectmode10) | Yes | Audio effect mode to set. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | ----------------------------------------------| +| 6800101 | Invalid parameter error. Return by callback. | + **Example** ```js @@ -4893,6 +5061,14 @@ Sets an audio effect mode. This API uses a promise to return the result. | -------------- | ------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | ---------------------------------------------| +| 6800101 | Invalid parameter error. Return by promise. | + **Example** ```js 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 a8188ec8afa535a6d0ba5bc3e2bbd0fb32b8458c..4528a12c607d902868dc6b279f6f9f1bf80843ad 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) { @@ -348,11 +367,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 { - preferences = data_preferences.getPreferencesSync(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + preferences = data_preferences.getPreferencesSync(context, options); } catch(err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); } @@ -362,12 +384,16 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -let preferences = null; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - preferences = data_preferences.getPreferencesSync(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + preferences = data_preferences.getPreferencesSync(this.context, options); } catch(err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); } @@ -408,10 +434,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; @@ -427,11 +455,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; @@ -483,13 +513,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) { @@ -501,14 +533,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) { @@ -553,10 +587,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; @@ -572,11 +609,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; @@ -631,13 +671,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) { @@ -649,14 +692,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) { @@ -694,9 +740,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; @@ -712,11 +760,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; @@ -762,12 +812,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) { @@ -779,14 +831,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) { @@ -824,7 +878,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); } @@ -836,9 +890,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); } @@ -882,9 +936,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; @@ -900,11 +956,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; @@ -959,12 +1018,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) { @@ -976,14 +1037,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) { @@ -1030,7 +1094,8 @@ FA model: import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCacheSync(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.removePreferencesFromCacheSync(context, options); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -1040,11 +1105,13 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCacheSync(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCacheSync(this.context, options); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -1090,7 +1157,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; @@ -1129,9 +1196,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) { @@ -1164,7 +1231,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); @@ -1189,14 +1256,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); @@ -1223,11 +1290,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) { @@ -1282,7 +1349,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; @@ -1323,7 +1390,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) { @@ -1377,7 +1444,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; @@ -1387,7 +1454,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); } @@ -1419,15 +1486,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); } @@ -1458,7 +1525,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 { @@ -1489,7 +1556,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; @@ -1529,7 +1596,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) { @@ -1581,7 +1648,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; @@ -1615,7 +1682,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) { @@ -1642,7 +1709,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; @@ -1676,7 +1743,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) { @@ -1722,29 +1789,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."); }) }) }) @@ -1781,24 +1850,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; @@ -1815,17 +1886,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; @@ -1838,7 +1913,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; @@ -1849,16 +1924,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; @@ -1890,31 +1964,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) { @@ -1940,31 +2018,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/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 247f7fe55d79701c01435ae36bf63c7a505338e9..afc8624a772203fd072a99e5bd03408c9ee6fddb 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -20,6 +20,7 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal This API can be used only in the stage model. > **NOTE** +> > This API is deprecated since API version 9. Use [getPhotoAccessHelper](js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) instead. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -44,7 +45,7 @@ const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); ``` -**Example (API version 8)** +**Example (from API version 8)** ```js import featureAbility from '@ohos.ability.featureAbility'; @@ -62,6 +63,7 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal This API can be used only in the FA model. > **NOTE** +> > This API is deprecated since API version 9. There is no substitute API. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -344,7 +346,7 @@ Creates a media asset. This API uses a promise to return the result. | ------------ | ------------------------ | ---- | ------------------------------------------------------------ | | mediaType | [MediaType](#mediatype8) | Yes | Media type. | | displayName | string | Yes | File name to display. | -| relativePath | string | Yes | Relative path of the file, which can be obtained by [getPublicDirectory](#getpublicdirectory8).| +| relativePath | string | Yes | Relative path of the file, which can be obtained by **getPublicDirectory**.| **Return value** @@ -557,7 +559,7 @@ Obtains albums. This API uses an asynchronous callback to return the result. > **NOTE** > > - This API is deprecated since API version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums) instead. -> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). +> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). **Required permissions**: ohos.permission.READ_MEDIA @@ -597,7 +599,7 @@ Obtains albums. This API uses a promise to return the result. > **NOTE** > > - This API is deprecated since API version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums-2) instead. -> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). +> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). **Required permissions**: ohos.permission.READ_MEDIA @@ -666,6 +668,7 @@ Releases this **MediaLibrary** instance. Call this API when you no longer need to use the APIs in the **MediaLibrary** instance. > **NOTE** +> > This API is deprecated since API version 9. Use [release](js-apis-photoAccessHelper.md#release-1) instead. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 80b916acdf6b49010cdb8eda3f85473b06f5c37d..4db7f5817e3287395f1a24b87dd68eb2dab70739 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -3226,6 +3226,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur ```js import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); + let localId: number = 100; accountManager.isOsAccountVerified(localId).then((isVerified: boolean) => { console.log('isOsAccountVerified successfully, isVerified: ' + isVerified); }).catch((err: BusinessError) => { @@ -3457,7 +3458,7 @@ Obtains the OS account ID based on the domain account information. This API uses ```js import { BusinessError } from '@ohos.base'; - let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + let domainInfo: account_osAccount.DomainAccountInfo = {domain: 'testDomain', accountName: 'testAccountName'}; let accountManager = account_osAccount.getAccountManager(); accountManager.getOsAccountLocalIdFromDomain(domainInfo, (err: BusinessError, localId: number) => { if (err) { @@ -3499,7 +3500,7 @@ Obtains the OS account ID based on the domain account information. This API uses ```js import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + let domainInfo: account_osAccount.DomainAccountInfo = {domain: 'testDomain', accountName: 'testAccountName'}; accountManager.getOsAccountLocalIdFromDomain(domainInfo).then((localId: number) => { console.log('getOsAccountLocalIdFromDomain successfully, localId: ' + localId); }).catch((err: BusinessError) => { diff --git a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md index b7bf574032b04eb83909c0006bce06a5e3900560..3f524bb931a982611e15742b4c19035309c5943c 100644 --- a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md +++ b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md @@ -84,12 +84,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getAssets'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; @@ -97,7 +96,7 @@ async function example() { phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => { if (fetchResult != undefined) { console.info('fetchResult success'); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let photoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName : ' + photoAsset.displayName); } @@ -142,21 +141,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('getAssets'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fetchResult = await phAccessHelper.getAssets(fetchOptions); if (fetchResult != undefined) { console.info('fetchResult success'); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let photoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName :' + photoAsset.displayName); } @@ -201,7 +198,7 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts async function example() { console.info('createAssetDemo'); - let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let testFileName = 'testFile' + Date.now() + '.jpg'; phAccessHelper.createAsset(testFileName, (err, photoAsset) => { if (photoAsset != undefined) { console.info('createAsset file displayName' + photoAsset.displayName); @@ -250,13 +247,11 @@ For details about the error codes, see [File Management Error Codes](../errorcod **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createAssetDemo'); try { - let testFileName: string = 'testFile' + Date.now() + '.jpg'; - let photoAsset: photoAccessHelper.photoAsset = await phAccessHelper.createAsset(testFileName); + let testFileName = 'testFile' + Date.now() + '.jpg'; + let photoAsset = await phAccessHelper.createAsset(testFileName); console.info('createAsset file displayName' + photoAsset.displayName); console.info('createAsset successfully'); } catch (err) { @@ -298,12 +293,10 @@ For details about the error codes, see [File Management Error Codes](../errorcod **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createAssetDemo'); - let testFileName: string = 'testFile' + Date.now() + '.jpg'; - let createOption: photoAccessHelper.CreateOptions = { + let testFileName = 'testFile' + Date.now() + '.jpg'; + let createOption = { subtype: photoAccessHelper.PhotoSubtype.DEFAULT } phAccessHelper.createAsset(testFileName, createOption, (err, photoAsset) => { @@ -355,16 +348,14 @@ For details about the error codes, see [File Management Error Codes](../errorcod **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createAssetDemo'); try { - let testFileName: string = 'testFile' + Date.now() + '.jpg'; - let photoAccessHelper: photoAccessHelper.PhotoAccessHelper = { + let testFileName = 'testFile' + Date.now() + '.jpg'; + let createOption = { subtype: photoAccessHelper.PhotoSubtype.DEFAULT } - let photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName, createOption); + let photoAsset = await phAccessHelper.createAsset(testFileName, createOption); console.info('createAsset file displayName' + photoAsset.displayName); console.info('createAsset successfully'); } catch (err) { @@ -403,13 +394,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createAssetDemo'); - let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; - let extension: string = 'jpg'; - let options: photoAccessHelper.FetchOptions = { + let photoType = photoAccessHelper.PhotoType.IMAGE; + let extension = 'jpg'; + let options = { title: 'testPhoto' } phAccessHelper.createAsset(photoType, extension, options, (err, uri) => { @@ -452,12 +441,10 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createAssetDemo'); - let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; - let extension: string = 'jpg'; + let photoType = photoAccessHelper.PhotoType.IMAGE; + let extension = 'jpg'; phAccessHelper.createAsset(photoType, extension, (err, uri) => { if (uri != undefined) { console.info('createAsset uri' + uri); @@ -504,17 +491,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createAssetDemo'); try { - let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; - let extension: string = 'jpg'; - let options: photoAccessHelper.FetchOptions = { + let photoType = photoAccessHelper.PhotoType.IMAGE; + let extension = 'jpg'; + let options = { title: 'testPhoto' } - let uri: photoAccessHelper.PhotoAccess = await phAccessHelper.createAsset(photoType, extension, options); + let uri = await phAccessHelper.createAsset(photoType, extension, options); console.info('createAsset uri' + uri); console.info('createAsset successfully'); } catch (err) { @@ -560,8 +545,6 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createAlbumDemo'); let albumName = 'newAlbumName' + new Date().getTime(); @@ -662,20 +645,18 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { // Delete the album named newAlbumName. console.info('deleteAlbumsDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions: photoAccessHelper.FetchOptions = { + let fetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); phAccessHelper.deleteAlbums([album], (err) => { if (err) { console.error('deletePhotoAlbumsCallback failed with err: ' + err); @@ -726,20 +707,18 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { // Delete the album named newAlbumName. console.info('deleteAlbumsDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions: photoAccessHelper.FetchOptions = { + let fetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); phAccessHelper.deleteAlbums([album]).then(() => { console.info('deletePhotoAlbumsPromise successfully'); }).catch((err) => { @@ -782,15 +761,13 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { // Obtain the album named newAlbumName. console.info('getAlbumsDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions: photoAccessHelper.FetchOptions = { + let fetchOptions = { fetchColumns: [], predicates: predicates }; @@ -803,7 +780,7 @@ async function example() { console.error('getAlbumsCallback fetchResult is undefined'); return; } - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + let album = await fetchResult.getFirstObject(); console.info('getAlbumsCallback successfully, albumName: ' + album.albumName); fetchResult.close(); }); @@ -841,8 +818,6 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { // Obtain the system album VIDEO, which is preset by default. console.info('getAlbumsDemo'); @@ -855,7 +830,7 @@ async function example() { console.error('getAlbumsCallback fetchResult is undefined'); return; } - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + let album = await fetchResult.getFirstObject(); console.info('getAlbumsCallback successfully, albumUri: ' + album.albumUri); fetchResult.close(); }); @@ -900,15 +875,13 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { // Obtain the album named newAlbumName. console.info('getAlbumsDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions: photoAccessHelper.FetchOptions = { + let fetchOptions = { fetchColumns: [], predicates: predicates }; @@ -917,7 +890,7 @@ async function example() { console.error('getAlbumsPromise fetchResult is undefined'); return; } - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + let album = await fetchResult.getFirstObject(); console.info('getAlbumsPromise successfully, albumName: ' + album.albumName); fetchResult.close(); }).catch((err) => { @@ -958,13 +931,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('deleteAssetDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; @@ -1026,13 +997,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('deleteDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; @@ -1086,26 +1055,24 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('registerChangeDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let photoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName : ' + photoAsset.displayName); } - let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { + let onCallback1 = (changeData) => { console.info('onCallback1 success, changData: ' + JSON.stringify(changeData)); //file had changed, do something } - let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { + let onCallback2 = (changeData) => { console.info('onCallback2 success, changData: ' + JSON.stringify(changeData)); //file had changed, do something } @@ -1153,25 +1120,23 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('offDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let photoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName : ' + photoAsset.displayName); } - let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { + let onCallback1 = (changeData) => { console.info('onCallback1 on'); } - let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { + let onCallback2 = (changeData) => { console.info('onCallback2 on'); } // Register onCallback1. @@ -1194,7 +1159,7 @@ async function example() { createDeleteRequest(uriList: Array<string>, callback: AsyncCallback<void>): void; -Creates a dialog box for deleting photos. This API uses an asynchronous callback to return the result. The deleted photos are moved to the trash. +Creates a dialog box for deleting media files. This API uses an asynchronous callback to return the result. The deleted media files are moved to the trash. **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO @@ -1204,7 +1169,7 @@ Creates a dialog box for deleting photos. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| uriList | Array<string> | Yes | URIs of the media files to delete.| +| uriList | Array<string> | Yes | URIs of the media files to delete. A maximum of 300 media files can be deleted.| | callback | AsyncCallback<void> | Yes | Callback that returns no value.| **Error codes** @@ -1219,13 +1184,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createDeleteRequestDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; @@ -1254,7 +1217,7 @@ async function example() { createDeleteRequest(uriList: Array<string>): Promise<void>; -Creates a dialog box for deleting photos. This API uses a promise to return the result. The deleted photos are moved to the trash. +Creates a dialog box for deleting media files. This API uses a promise to return the result. The deleted media files are moved to the trash. **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO @@ -1264,7 +1227,7 @@ Creates a dialog box for deleting photos. This API uses a promise to return the | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| uriList | Array<string> | Yes | URIs of the media files to delete.| +| uriList | Array<string> | Yes | URIs of the media files to delete. A maximum of 300 media files can be deleted.| **Return value** @@ -1284,13 +1247,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('createDeleteRequestDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; @@ -1352,41 +1313,38 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { - console.info('getPhotoIndexDemo'); - let predicatesForGetAsset: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOp: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicatesForGetAsset - }; - //Obtain the uri of the album - let albumFetchResult: photoAccessHelper.FetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - predicates.orderByAsc("add_modified"); - let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates - }; - let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let expectIndex = 1; - //Obtain the uri of the second file - let photoAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getObjectByPosition(expectIndex); + try { + console.info('getPhotoIndexDemo'); + let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); + let fetchOp = { + fetchColumns: [], + predicates: predicatesForGetAsset + }; + // Obtain the uri of the album + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); + let album = await albumFetchResult.getFirstObject(); + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.orderByAsc(photoAccessHelper.PhotoKeys.DATE_MODIFIED); + let fetchOptions = { + fetchColumns: [photoAccessHelper.PhotoKeys.DATE_MODIFIED], + predicates: predicates + }; + let photoFetchResult = await album.getAssets(fetchOptions); + let expectIndex = 1; + // Obtain the uri of the second file + let photoAsset = await photoFetchResult.getObjectByPosition(expectIndex); - photoAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => { - try { + phAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => { if (err == undefined) { console.info(`getPhotoIndex successfully and index is : ${index}`); } else { console.info(`getPhotoIndex failed;`); } - } catch (error) { - console.info(`getPhotoIndex failed; error: ${error}`); - } + }); + } catch (error) { + console.info(`getPhotoIndex failed; error: ${error}`); } } ``` @@ -1429,37 +1387,36 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { - console.info('getPhotoIndexDemo'); - let predicatesForGetAsset: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOp: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicatesForGetAsset - }; - //Obtain the uri of the album - let albumFetchResult: photoAccessHelper.FetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - predicates.orderByAsc("add_modified"); - let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates - }; - let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let expectIndex = 1; - //Obtain the uri of the second file - let photoAsset = await photoFetchResult.getObjectByPosition(expectIndex); - - photoAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions) - .then((index) => { - console.info(`getPhotoIndex successfully and index is : ${index}`); - }).catch((err) => { + try { + console.info('getPhotoIndexDemo'); + let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); + let fetchOp = { + fetchColumns: [], + predicates: predicatesForGetAsset + }; + // Obtain the uri of the album + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); + let album = await albumFetchResult.getFirstObject(); + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.orderByAsc(photoAccessHelper.PhotoKeys.DATE_MODIFIED); + let fetchOptions = { + fetchColumns: [photoAccessHelper.PhotoKeys.DATE_MODIFIED], + predicates: predicates + }; + let photoFetchResult = await album.getAssets(fetchOptions); + let expectIndex = 1; + // Obtain the uri of the second file + let photoAsset = await photoFetchResult.getObjectByPosition(expectIndex); + phAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions).then((index) => { + console.info(`getPhotoIndex successfully and index is : ${index}`); + }).catch((err) => { console.info(`getPhotoIndex failed; error: ${err}`); - }) + }); + } catch (error) { + console.info(`getPhotoIndex failed; error: ${error}`); + } } ``` @@ -1584,21 +1541,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('photoAssetGetDemo'); try { - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE; - let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title.toString()); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset = await fetchResult.getFirstObject(); + let title = photoAccessHelper.PhotoKeys.TITLE; + let photoAssetTitle = photoAsset.get(title.toString()); console.info('photoAsset Get photoAssetTitle = ', photoAssetTitle); } catch (err) { console.error('release failed. message = ', err); @@ -1633,20 +1588,18 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('photoAssetSetDemo'); try { - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE.toString(); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset = await fetchResult.getFirstObject(); + let title = photoAccessHelper.PhotoKeys.TITLE.toString(); photoAsset.set(title, 'newTitle'); } catch (err) { console.error('release failed. message = ', err); @@ -1682,25 +1635,23 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('commitModifyDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOption = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE.toString(); - let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset = await fetchResult.getFirstObject(); + let title = photoAccessHelper.PhotoKeys.TITLE.toString(); + let photoAssetTitle = photoAsset.get(title); console.info('photoAsset get photoAssetTitle = ', photoAssetTitle); photoAsset.set(title, 'newTitle2'); photoAsset.commitModify((err) => { if (err == undefined) { - let newPhotoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); + let newPhotoAssetTitle = photoAsset.get(title); console.info('photoAsset get newPhotoAssetTitle = ', newPhotoAssetTitle); } else { console.error('commitModify failed, message =', err); @@ -1737,25 +1688,23 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('commitModifyDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE.toString(); - let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset = await fetchResult.getFirstObject(); + let title = photoAccessHelper.PhotoKeys.TITLE.toString(); + let photoAssetTitle = photoAsset.get(title); console.info('photoAsset get photoAssetTitle = ', photoAssetTitle); photoAsset.set(title, 'newTitle3'); try { await photoAsset.commitModify(); - let newPhotoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); + let newPhotoAssetTitle = photoAsset.get(title); console.info('photoAsset get newPhotoAssetTitle = ', newPhotoAssetTitle); } catch (err) { console.error('release failed. message = ', err); @@ -1798,7 +1747,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts async function example() { console.info('openDemo'); - let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let testFileName = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); photoAsset.open('rw', (err, fd) => { if (fd != undefined) { @@ -1852,7 +1801,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err async function example() { console.info('openDemo'); try { - let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let testFileName = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); let fd = await photoAsset.open('rw'); if (fd != undefined) { @@ -1898,7 +1847,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts async function example() { console.info('getReadOnlyFdDemo'); - let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let testFileName = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); photoAsset.getReadOnlyFd((err, fd) => { if (fd != undefined) { @@ -1943,7 +1892,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err async function example() { console.info('getReadOnlyFdDemo'); try { - let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let testFileName = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); let fd = await photoAsset.getReadOnlyFd(); if (fd != undefined) { @@ -1985,18 +1934,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('closeDemo'); try { - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const photoAsset = await fetchResult.getFirstObject(); let fd = await photoAsset.open('rw'); console.info('file fd', fd); @@ -2045,18 +1992,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('closeDemo'); try { - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); let fd = await asset.open('rw'); console.info('file fd', fd); @@ -2096,16 +2041,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getThumbnailDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); console.info('asset displayName = ', asset.displayName); asset.getThumbnail((err, pixelMap) => { @@ -2147,20 +2091,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -import image from '@ohos.multimedia.image'; - - async function example() { console.info('getThumbnailDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let size: image.Size = { width: 720, height: 720 }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let size = { width: 720, height: 720 }; + let fetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); console.info('asset displayName = ', asset.displayName); asset.getThumbnail(size, (err, pixelMap) => { @@ -2207,19 +2147,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -import image from '@ohos.multimedia.image'; - async function example() { console.info('getThumbnailDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let size: image.Size = { width: 720, height: 720 }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let size = { width: 720, height: 720 }; + let fetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); console.info('asset displayName = ', asset.displayName); asset.getThumbnail(size).then((pixelMap) => { @@ -2262,17 +2199,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('setFavoriteDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setFavorite(true, (err) => { if (err == undefined) { @@ -2321,17 +2256,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('setFavoriteDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setFavorite(true).then(function () { console.info('setFavorite successfully'); @@ -2375,17 +2308,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { console.info('setHiddenDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setHidden(true, (err) => { if (err == undefined) { @@ -2436,20 +2367,18 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { // Restore a file from a hidden album. Before the operation, ensure that the file exists in the hidden album. console.info('setHiddenDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumList: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.HIDDEN); + let albumList = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.HIDDEN); const album = await albumList.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let fetchResult = await album.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setHidden(false).then(() => { console.info('setHidden successfully'); @@ -2465,7 +2394,7 @@ getExif(): Promise<string> Obtains a JSON string consisting of the EXIF tags of this JPG image. This API uses a promise to return the result. -**CAUTION**
This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **js-apis-photoAccessHelper.md**. These two fields must be passed in via **fetchColumns**. +**CAUTION**
This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **PhotoKeys.USER_COMMENT**. These two fields must be passed in via **fetchColumns**. **System API**: This is a system API. @@ -2503,6 +2432,7 @@ For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#proper | GPSDateStamp | GPS date stamp.| | ImageDescription | Image description.| | Make | Camera vendor.| +| MakeNote | Camera vendor.| | Model | Model.| | PhotoMode | Photo mode.| | SensitivityType | Sensitivity type.| @@ -2524,22 +2454,23 @@ For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#proper ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { try { console.info('getExifDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [ 'all_exif', photoKeys.USER_COMMENT], + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.isNotNull('all_exif') + let fetchOptions = { + fetchColumns: ['all_exif', photoAccessHelper.PhotoKeys.USER_COMMENT], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getExifDemo fileAsset displayName: ' + JSON.stringify(fileAsset.displayName)); let exifMessage = await fileAsset.getExif(); let userCommentKey = 'UserComment'; let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]); + console.info('getExifDemo userComment: ' + JSON.stringify(userComment)); fetchResult.close(); } catch (err) { console.error('getExifDemoCallback failed with error: ' + err); @@ -2553,7 +2484,7 @@ getExif(callback: AsyncCallback<string>): void Obtains a JSON string consisting of the EXIF tags of this JPG image. This API uses an asynchronous callback to return the result. -**CAUTION**
This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **ImageVideoKey.USER_COMMENT**. These two fields must be passed in via **fetchColumns**. +**CAUTION**
This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **PhotoKeys.USER_COMMENT**. These two fields must be passed in via **fetchColumns**. **System API**: This is a system API. @@ -2591,6 +2522,7 @@ For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#proper | GPSDateStamp | GPS date stamp.| | ImageDescription | Image description.| | Make | Camera vendor.| +| MakeNote | Camera vendor.| | Model | Model.| | PhotoMode | Photo mode.| | SensitivityType | Sensitivity type.| @@ -2612,23 +2544,24 @@ For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#proper ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { try { console.info('getExifDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [ 'all_exif', photoKeys.USER_COMMENT], + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.isNotNull('all_exif') + let fetchOptions = { + fetchColumns: ['all_exif', photoAccessHelper.PhotoKeys.USER_COMMENT], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getExifDemo fileAsset displayName: ' + JSON.stringify(fileAsset.displayName)); let userCommentKey = 'UserComment'; fileAsset.getExif((err, exifMessage) => { if (exifMessage != undefined) { let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]); + console.info('getExifDemo userComment: ' + JSON.stringify(userComment)); } else { console.error('getExif failed, message = ', err); } @@ -2670,19 +2603,17 @@ Sets user comment information of an image or video. This API uses a promise to r ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { try { console.info('setUserCommentDemo') - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); let userComment = 'test_set_user_comment'; await fileAsset.setUserComment(userComment); } catch (err) { @@ -2716,19 +2647,17 @@ Sets user comment information of an image or video. This API uses an asynchronou ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - async function example() { try { console.info('setUserCommentDemo') - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); let userComment = 'test_set_user_comment'; fileAsset.setUserComment(userComment, (err) => { if (err === undefined) { @@ -2773,16 +2702,15 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getCountDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const fetchCount = fetchResult.getCount(); console.info('fetchCount = ', fetchCount); } @@ -2814,18 +2742,17 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); const fetchCount = fetchResult.getCount(); console.info('count:' + fetchCount); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getLastObject(); + let photoAsset = await fetchResult.getLastObject(); if (fetchResult.isAfterLast()) { console.info('photoAsset isAfterLast displayName = ', photoAsset.displayName); } else { @@ -2854,17 +2781,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('fetchResultCloseDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.close(); console.info('close succeed.'); } catch (err) { @@ -2899,16 +2825,15 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getFirstObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getFirstObject((err, photoAsset) => { if (photoAsset != undefined) { console.info('photoAsset displayName: ', photoAsset.displayName); @@ -2945,17 +2870,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getFirstObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset = await fetchResult.getFirstObject(); console.info('photoAsset displayName: ', photoAsset.displayName); } ``` @@ -2986,16 +2910,15 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getNextObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); await fetchResult.getFirstObject(); if (fetchResult.isAfterLast()) { fetchResult.getNextObject((err, photoAsset) => { @@ -3035,16 +2958,15 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getNextObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); await fetchResult.getFirstObject(); if (fetchResult.isAfterLast()) { let photoAsset = await fetchResult.getNextObject(); @@ -3079,16 +3001,15 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getLastObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getLastObject((err, photoAsset) => { if (photoAsset != undefined) { console.info('photoAsset displayName: ', photoAsset.displayName); @@ -3125,17 +3046,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getLastObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getLastObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset = await fetchResult.getLastObject(); console.info('photoAsset displayName: ', photoAsset.displayName); } ``` @@ -3167,16 +3087,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getObjectByPositionDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getObjectByPosition(0, (err, photoAsset) => { if (photoAsset != undefined) { console.info('photoAsset displayName: ', photoAsset.displayName); @@ -3219,17 +3138,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getObjectByPositionDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getObjectByPosition(0); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset = await fetchResult.getObjectByPosition(0); console.info('photoAsset displayName: ', photoAsset.displayName); } ``` @@ -3260,16 +3178,15 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getAllObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getAllObjects((err, photoAssetList) => { if (photoAssetList != undefined) { console.info('photoAssetList length: ', photoAssetList.length); @@ -3306,17 +3223,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getAllObjectDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAssetList: photoAccessHelper.PhotoAsset = await fetchResult.getAllObjects(); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAssetList = await fetchResult.getAllObjects(); console.info('photoAssetList length: ', photoAssetList.length); } ``` @@ -3367,16 +3283,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumGetAssetsDemoCallback'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchOption: photoAccessHelper.FetchOptions = { + let fetchOption = { fetchColumns: [], predicates: predicates }; @@ -3426,17 +3341,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumGetAssetsDemoPromise'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchOption: photoAccessHelper.FetchOptions = { + let fetchOption = { fetchColumns: [], predicates: predicates }; @@ -3478,12 +3392,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumCommitModifyDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { fetchColumns: [], predicates: predicates }; @@ -3528,12 +3441,11 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumCommitModifyDemo'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { fetchColumns: [], predicates: predicates }; @@ -3577,20 +3489,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('addAssetsDemoCallback'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.addAssets([asset], (err) => { if (err === undefined) { console.info('album addAssets successfully'); @@ -3638,20 +3549,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('addAssetsDemoPromise'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await phAccessHelper.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.addAssets([asset]).then(() => { console.info('album addAssets successfully'); }).catch((err) => { @@ -3692,20 +3602,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('removeAssetsDemoCallback'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.removeAssets([asset], (err) => { if (err === undefined) { console.info('album removeAssets successfully'); @@ -3753,20 +3662,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('removeAssetsDemoPromise'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.removeAssets([asset]).then(() => { console.info('album removeAssets successfully'); }).catch((err) => { @@ -3810,20 +3718,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('recoverAssetsDemoCallback'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.recoverAssets([asset], (err) => { if (err === undefined) { console.info('album recoverAssets successfully'); @@ -3874,20 +3781,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('recoverAssetsDemoPromise'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.recoverAssets([asset]).then(() => { console.info('album recoverAssets successfully'); }).catch((err) => { @@ -3933,20 +3839,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('deleteAssetsDemoCallback'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.deleteAssets([asset], (err) => { if (err === undefined) { console.info('album deleteAssets successfully'); @@ -3999,20 +3904,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('deleteAssetsDemoPromise'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.deleteAssets([asset]).then(() => { console.info('album deleteAssets successfully'); }).catch((err) => { @@ -4058,20 +3962,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('setCoverUriDemoCallback'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.setCoverUri(asset.uri, (err) => { if (err === undefined) { console.info('album setCoverUri successfully'); @@ -4124,20 +4027,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('setCoverUriDemoCallback'); - let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption: photoAccessHelper.FetchOptions = { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { fetchColumns: [], predicates: predicates }; - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); - let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); album.setCoverUri(asset.uri, (err) => { if (err === undefined) { console.info('album setCoverUri successfully'); diff --git a/en/application-dev/reference/apis/js-apis-userFileManager.md b/en/application-dev/reference/apis/js-apis-userFileManager.md index ba865a7568afeae0feb7dfbf84f080652b9dc726..dc8155c7ffde3fae211a6595e3ae541e5fa2dda8 100644 --- a/en/application-dev/reference/apis/js-apis-userFileManager.md +++ b/en/application-dev/reference/apis/js-apis-userFileManager.md @@ -1433,37 +1433,35 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPhotoIndexDemo'); - let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); - let fetchOp = { - fetchColumns: [], - predicates: predicatesForGetAsset - }; - //Obtain the uri of the album - let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubtype.FAVORITE, fetchOp); - let album = await albumFetchResult.getFirstObject(); - - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.orderByAsc("add_modified"); - let fetchOptions = { - fetchColumns: [], - predicates: predicates - }; - let photoFetchResult = await album.getPhotoAssets(fetchOptions); - let expectIndex = 1; - //Obtain the uri of the second file - let photoAsset = await photoFetchResult.getPositionObject(expectIndex); - - mgr.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => { - try { + try { + console.info('getPhotoIndexDemo'); + let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); + let fetchOp = { + fetchColumns: [], + predicates: predicatesForGetAsset + }; + // Obtain the uri of the album + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.FAVORITE, fetchOp); + let album = await albumFetchResult.getFirstObject(); + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.orderByAsc(userFileManager.ImageVideoKey.DATE_MODIFIED); + let fetchOptions = { + fetchColumns: [userFileManager.ImageVideoKey.DATE_MODIFIED], + predicates: predicates + }; + let photoFetchResult = await album.getPhotoAssets(fetchOptions); + let expectIndex = 1; + // Obtain the uri of the second file + let photoAsset = await photoFetchResult.getPositionObject(expectIndex); + mgr.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => { if (err == undefined) { console.info(`getPhotoIndex successfully and index is : ${index}`); } else { console.info(`getPhotoIndex failed;`); } - } catch (error) { - console.info(`getPhotoIndex failed; error: ${error}`); - } + }); + } catch (error) { + console.info(`getPhotoIndex failed; error: ${error}`); } } ``` @@ -1508,33 +1506,34 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPhotoIndexDemo'); - let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); - let fetchOp = { - fetchColumns: [], - predicates: predicatesForGetAsset - }; - //Obtain the uri of the album - let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubtype.FAVORITE, fetchOp); - let album = await albumFetchResult.getFirstObject(); - - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.orderByAsc("add_modified"); - let fetchOptions = { - fetchColumns: [], - predicates: predicates - }; - let photoFetchResult = await album.getPhotoAssets(fetchOptions); - let expectIndex = 1; - //Obtain the uri of the second file - let photoAsset = await photoFetchResult.getPositionObject(expectIndex); - - mgr.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions) - .then((index) => { - console.info(`getPhotoIndex successfully and index is : ${index}`); - }).catch((err) => { + try { + console.info('getPhotoIndexDemo'); + let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); + let fetchOp = { + fetchColumns: [], + predicates: predicatesForGetAsset + }; + // Obtain the uri of the album + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.FAVORITE, fetchOp); + let album = await albumFetchResult.getFirstObject(); + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.orderByAsc(userFileManager.ImageVideoKey.DATE_MODIFIED); + let fetchOptions = { + fetchColumns: [userFileManager.ImageVideoKey.DATE_MODIFIED], + predicates: predicates + }; + let photoFetchResult = await album.getPhotoAssets(fetchOptions); + let expectIndex = 1; + // Obtain the uri of the second file + let photoAsset = await photoFetchResult.getPositionObject(expectIndex); + mgr.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions).then((index) => { + console.info(`getPhotoIndex successfully and index is : ${index}`); + }).catch((err) => { console.info(`getPhotoIndex failed; error: ${err}`); - }) + }); + } catch (error) { + console.info(`getPhotoIndex failed; error: ${error}`); + } } ``` @@ -2565,15 +2564,18 @@ async function example() { try { console.info('getExifDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.isNotNull('all_exif') let fetchOptions = { - fetchColumns: [ 'all_exif', ImageVideoKey.USER_COMMENT], + fetchColumns: ['all_exif', userFileManager.ImageVideoKey.USER_COMMENT], predicates: predicates }; let fetchResult = await mgr.getPhotoAssets(fetchOptions); let fileAsset = await fetchResult.getFirstObject(); + console.info('getExifDemo fileAsset displayName: ' + JSON.stringify(fileAsset.displayName)); let exifMessage = await fileAsset.getExif(); let userCommentKey = 'UserComment'; let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]); + console.info('getExifDemo userComment: ' + JSON.stringify(userComment)); fetchResult.close(); } catch (err) { console.error('getExifDemoCallback failed with error: ' + err); @@ -2651,16 +2653,19 @@ async function example() { try { console.info('getExifDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.isNotNull('all_exif') let fetchOptions = { - fetchColumns: [ 'all_exif', ImageVideoKey.USER_COMMENT], + fetchColumns: ['all_exif', userFileManager.ImageVideoKey.USER_COMMENT], predicates: predicates }; let fetchResult = await mgr.getPhotoAssets(fetchOptions); let fileAsset = await fetchResult.getFirstObject(); + console.info('getExifDemo fileAsset displayName: ' + JSON.stringify(fileAsset.displayName)); let userCommentKey = 'UserComment'; fileAsset.getExif((err, exifMessage) => { if (exifMessage != undefined) { let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]); + console.info('getExifDemo userComment: ' + JSON.stringify(userComment)); } else { console.error('getExif failed, message = ', err); } diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md index 3b8ae1031235123dc9490bcbbddc197828dcab67..356359d090cc5c58e8de06611e92838505d16993 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md @@ -72,7 +72,7 @@ Creates a **FormComponent** instance to display the provided widget. | Name | Description | | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | onAcquired(callback: (info: { id: number }) => void) | Triggered when a widget is obtained. This API returns the ID of the obtained widget. | -| onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information. | +| onError(callback: (info: { errcode: number, msg: string }) => void) | Triggered when an error occurs during component loading.
**errcode**: error code.
**msg**: error information.
For details, see [Form Error Codes](../errorcodes/errorcode-form.md). | | onRouter(callback: (info: any) => void) | Triggered when routing occurs for the widget. This API returns information in [routerEvent](../js-service-widget-ui/js-service-widget-syntax-hml.md#event-binding).| | onUninstall(callback: (info: { id: number }) => void) | Triggered when a widget is uninstalled. This API returns the ID of the uninstalled widget. | diff --git a/en/contribute/template/native-template.md b/en/contribute/template/native-template.md index a13f5366ede2f7e997111c96e3d4b002c85c3026..e4e027262af5bbc92a8c50ad38d8132ce55f02b3 100644 --- a/en/contribute/template/native-template.md +++ b/en/contribute/template/native-template.md @@ -8,21 +8,16 @@ ``` /** - * @addtogroup Module name + * @addtogroup Followed by a module name. * @{ * * @brief Outline the functionality of the module in one sentence. * * Describe the main functionalities, use scenarios, and use suggestions of the module. Focus on the logical concepts involved in this module, their relationships, and their functionalities in an application. - * For example, for choreographer, describe its functionalities and how to use it. - * Choreographer orchestrates the timing of frame rendering. It is a C implementation in Java. Applications can use choreographer to arrange the proper timing of frame rendering as follows: - * 1. Register a callback function with choreographer. - * 2. The callback function is called when it is time to start the next frame, with the FrameCallbackData parameter returned. - * 3. Perform processing on the callback. - * 4. The SF performs conversion based on the return value of the callback. + * Introduce the functionalities of each concept, and then introduce how to use it. * In the detailed description, if there are multiple paragraphs, end each paragraph with \n.\n * - * @since OS version + * @since Followed by an OS version. */ ... @@ -34,14 +29,15 @@ ``` /** - * @file Header file name + * @file Followed by a header file name. * * @brief Outline the functionality of the header file in one sentence. * * Describe the main functionalities, use scenarios, and use suggestions of this class or interface. Focus on the logical concepts involved in this class, their relationships, and their functionalities in an application.\n * In the detailed description, if there are multiple paragraphs, end each paragraph with \n.\n - * @library Name of the .so file to be linked when the header file interface is referenced - * @since OS version + * @library Followed by the name of the .so file to be linked when the header file interface is referenced + * @syscap Followed by the system capability of the header file. + * @since Followed by an OS version. */ ``` @@ -54,8 +50,8 @@ * Describe the functionalities, use restrictions, use suggestions, and value ranges of the macro definition, constant, and variable, as well as consequences when boundary values and invalid values are used.\n * In the detailed description, if there are multiple paragraphs, end each paragraph with \n.\n * - * @deprecated (Optional) Add this flag for a deprecated interface. Specify the version from which the interface is deprecated and the substitute interface. - * @since OS version + * @deprecated (Optional) Followed by 'since' plus an OS version. Add this flag for a deprecated variable. Specify the version from which the variable is deprecated, and provide the substitute variable. + * @since Followed by an OS version. */ ``` @@ -68,14 +64,18 @@ * Describe the functionalities, use scenarios, and use suggestions of the struct or union.\n * In the detailed description, if there are multiple paragraphs, end each paragraph with \n.\n * - * @deprecated (Optional) Add this flag for a deprecated interface. Specify the version from which the interface is deprecated and the substitute interface. - * @since OS version + * @deprecated (Optional) Followed by 'since' plus an OS version. Add this flag for a deprecated struct or union. Specify the version from which the struct or union is deprecated, and provide the substitute struct or union. + * @since Followed by an OS version. */ struct StructName { /** Describe the meaning of member 1. */ unsigned long StructMember1; /** Describe the meaning of member 2. */ unsigned long StructMember2; +/** Describe the meaning of member 3. + * @since (Optional) Followed by an OS version. Add this flag for a new member if its introduced version is different from the version of the struct. + */ +unsigned long StructMember3; }; ``` @@ -88,15 +88,19 @@ unsigned long StructMember2; * Describe the main functionalities, use scenarios, and use suggestions of the enum.\n * In the detailed description, if there are multiple paragraphs, end each paragraph with \n.\n * - * @deprecated (Optional) Add this flag for a deprecated interface. Specify the version from which the interface is deprecated and the substitute interface. - * @since OS version + * @deprecated (Optional) Followed by 'since' plus an OS version. Add this flag for a deprecated enum. Specify the version from which the enum is deprecated, and provide the substitute enum. + * @since Followed by an OS version. */ enum EnumName { - /** Describe the meaning of the enumerated value 1. */ + /** Describe the meaning of enumerated value 1. */ EnumMermber1, - /** Describe the meaning of the enumerated value 2. */ + /** Describe the meaning of enumerated value 2. + * @deprecated (Optional) Followed by 'since' plus an OS version. Add this flag for a deprecated enumerated value. Specify the version from which the enumerated value is deprecated. Do not delete the enumerated values, especially the enumerated values that are encoded in sequence. + */ EnumMermber2, - /** Describe the meaning of the enumerated value 3. */ + /** Describe the meaning of enumerated value 3. + * @since (Optional) Followed by an OS version. Add this flag for a new enumerated value if its introduced version is different from the version of the enum. + */ EnumMermber3 }; ``` @@ -111,10 +115,11 @@ enum EnumName { * In the detailed description, if there are multiple paragraphs, end each paragraph with \n.\n * * @param (Optional) Followed by the parameter name and description. Use one @param tag for each parameter. If the function does not have parameters, delete the tag. Content of the parameter description: 1. Parameter functionality, use restrictions, and use suggestions; 2. Value range of the parameter, and consequences when boundary values and invalid values are used; 3. Recommended or empirical values - * @return (Optional) Followed by the return value description. If the function does not return a value, delete the tag. + * @return (Optional) Followed by the return value description. Describe the meaning of each return value. If the function does not return a value, delete the tag. * @see (Optional) Followed by a function associated with the current function. Use one @see tag for each associated function. If the current function does not have associated functions, delete the tag. * @permission (Optional) Followed by the permission required to use the function. Use one @permission tag for each associated permission. If the function does not require any permission, delete the tag. - * @deprecated (Optional) Add this flag for a deprecated interface. Specify the version from which the interface is deprecated and the substitute interface. - * @since OS version + * @deprecated (Optional) Followed by 'since' plus an OS version. Add this flag for a deprecated function. Specify the version from which the function is deprecated. + * @useinstead Followed by the substitute function. + * @since Followed by an OS version. */ ``` diff --git a/en/release-notes/api-diff/v3.2-Release/js-apidiff-ability.md b/en/release-notes/api-diff/v3.2-Release/js-apidiff-ability.md index 5df16922c5938c685642ed5b918211f113db6179..710d2844fa7488f25112c0a775919683ed2a626b 100644 --- a/en/release-notes/api-diff/v3.2-Release/js-apidiff-ability.md +++ b/en/release-notes/api-diff/v3.2-Release/js-apidiff-ability.md @@ -257,7 +257,7 @@ |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: launchWant: Want;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: lastRequestWant: Want;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: callee: Callee;|@ohos.app.ability.UIAbility.d.ts| -|Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onCreate(want: Want, param: AbilityConstant.LaunchParam): void;|@ohos.app.ability.UIAbility.d.ts| +|Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onWindowStageCreate(windowStage: window.WindowStage): void;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onWindowStageDestroy(): void;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onWindowStageRestore(windowStage: window.WindowStage): void;|@ohos.app.ability.UIAbility.d.ts| @@ -265,7 +265,7 @@ |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onForeground(): void;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onBackground(): void;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onContinue(wantParam: { [key: string]: Object }): AbilityConstant.OnContinueResult;|@ohos.app.ability.UIAbility.d.ts| -|Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;|@ohos.app.ability.UIAbility.d.ts| +|Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onDump(params: Array\): Array\;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.UIAbility
Class name: UIAbility
Method or attribute name: onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult;|@ohos.app.ability.UIAbility.d.ts| |Added|NA|Module name: ohos.app.ability.Want
Class name: Want|@ohos.app.ability.Want.d.ts| diff --git a/en/release-notes/api-diff/v3.2-beta2/js-apidiff-ability.md b/en/release-notes/api-diff/v3.2-beta2/js-apidiff-ability.md index 07ce3517ee15ba3ff41fed47d55bea4044e59619..7292ca58856bb7ebe3c414d06db11b3e1bcbda16 100644 --- a/en/release-notes/api-diff/v3.2-beta2/js-apidiff-ability.md +++ b/en/release-notes/api-diff/v3.2-beta2/js-apidiff-ability.md @@ -73,5 +73,5 @@ The table below lists the APIs changes of the ability framework in OpenHarmony 3 | FormExtensionContext | FormExtensionContext | updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void;
updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\; | Deleted| | ServiceExtensionContext | ServiceExtensionContext | extensionAbilityInfo: ExtensionAbilityInfo; | Deleted| | ohos.application.appManager | appManager | getProcessRunningInfos(): Promise\>;
getProcessRunningInfos(callback: AsyncCallback\>): void; | Deprecated| -| ohos.application.Ability | Ability | old : onNewWant(want: Want): void;
new : onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Updated| -| ohos.application.Ability | Callee | old : on(method: string, callback: CaleeCallBack): void;
new : on(method: string, callback: CalleeCallBack): void; | Updated| +| ohos.application.Ability | Ability | old : onNewWant(want: Want): void;
new : onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; | Updated| +| ohos.application.Ability | Callee | old : on(method: string, callback: CaleeCallBack): void;
new : on(method: string, callback: CalleeCallBack): void; | Updated| \ No newline at end of file diff --git a/en/release-notes/api-diff/v3.2-beta5/js-apidiff-ability.md b/en/release-notes/api-diff/v3.2-beta5/js-apidiff-ability.md index d9b926892f358697064a18f0e9bc51a84a8860a9..cc47e4ba08c41593a82cc65ffb2f5b7e3124105f 100644 --- a/en/release-notes/api-diff/v3.2-beta5/js-apidiff-ability.md +++ b/en/release-notes/api-diff/v3.2-beta5/js-apidiff-ability.md @@ -1,4 +1,4 @@ -| Change Type | Old Version | New Version | d.ts File | +| Change Type | Old Version | New Version | .d.ts File | | ---- | ------ | ------ | -------- | |Added|NA|Module name: ohos.app.ability.dataUriUtils
Class name: dataUriUtils|@ohos.app.ability.dataUriUtils.d.ts| |Added|NA|Module name: ohos.app.ability.dataUriUtils
Class name: dataUriUtils
Method or attribute name: function getId(uri: string): number|@ohos.app.ability.dataUriUtils.d.ts| @@ -24,7 +24,7 @@ |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: launchWant: Want;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: lastRequestWant: Want;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: callee: Callee;|NA|@ohos.application.Ability.d.ts| -|Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onCreate(want: Want, param: AbilityConstant.LaunchParam): void;|NA|@ohos.application.Ability.d.ts| +|Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onWindowStageCreate(windowStage: window.WindowStage): void;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onWindowStageDestroy(): void;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onWindowStageRestore(windowStage: window.WindowStage): void;|NA|@ohos.application.Ability.d.ts| @@ -32,7 +32,7 @@ |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onForeground(): void;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onBackground(): void;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;|NA|@ohos.application.Ability.d.ts| -|Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;|NA|@ohos.application.Ability.d.ts| +|Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onConfigurationUpdated(config: Configuration): void;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: dump(params: Array): Array;|NA|@ohos.application.Ability.d.ts| |Deleted|Module name: ohos.application.Ability
Class name: Ability
Method or attribute name: onMemoryLevel(level: AbilityConstant.MemoryLevel): void;|NA|@ohos.application.Ability.d.ts| diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-filemanagement.md b/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-filemanagement.md deleted file mode 100644 index e56252a2767fe44e23a92e6eaf036e7a472c00cd..0000000000000000000000000000000000000000 --- a/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-filemanagement.md +++ /dev/null @@ -1,22 +0,0 @@ -# File Management Subsystem Changelog -## c1.filemanager.1 Change of the fileAccess Module -The **fileAccess** module will no longer support operations for obtaining thumbnails and media assets. - -**Change Impact** -1. Deleted **getThumbnail()**. -2. Deleted the **FILEKEY** of image and audio options. - -**Key API/Component Changes** -Deleted APIs: - -| Class | API | -| -------------- | ------------------------------------------------------------ | -| fileAccessHelper | getThumbnail(uri: string, size: image.Size): Promise;| -| fileAccessHelper | getThumbnail(uri: string, size: image.Size, callback: AsyncCallback): void;| - -Deleted options: -| Enum| Deleted Key Value| -| -------- | ---- | -| FileKey | DURATION = 'duration' | -| FileKey | WIDTH = 'width' | -| FileKey | HEIGHT = 'height' | diff --git a/zh-cn/application-dev/IDL/idl-guidelines.md b/zh-cn/application-dev/IDL/idl-guidelines.md index 5fe72b96cd3eacdd49f8646a2d152462a6739d61..276375f3f0987eab6cb26a59f7eadfc889368ee8 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)为例,可通过镜像站点获取。 diff --git a/zh-cn/application-dev/application-models/inputmethodextentionability.md b/zh-cn/application-dev/application-models/inputmethodextentionability.md index 517d12bae8fdbc56a3dbfe405936981c6f43caaf..9d01ef462f77b9708e1f46568ba317639934924a 100644 --- a/zh-cn/application-dev/application-models/inputmethodextentionability.md +++ b/zh-cn/application-dev/application-models/inputmethodextentionability.md @@ -61,13 +61,13 @@ export default class InputDemoService extends InputMethodExtensionAbility { - onCreate(want: Want) { - keyboardController.onCreate(this.context); // 初始化窗口并注册对输入法框架的事件监听 + onCreate(want: Want): void { + keyboardController.onCreate(this.context); // 初始化窗口并注册对输入法框架的事件监听 } - onDestroy() { + onDestroy(): void { console.log("onDestroy."); - this.keyboardController.onDestroy(); // 销毁窗口并去注册事件监听 + keyboardController.onDestroy(); // 销毁窗口并去注册事件监听 } } ``` @@ -78,7 +78,7 @@ import common from '@ohos.app.ability.common'; import display from '@ohos.display'; import inputMethodEngine from '@ohos.inputMethodEngine'; - import InputMethodExtensionContext from '@ohos.inputMethodExtensionContext'; + import InputMethodExtensionContext from '@ohos.InputMethodExtensionContext'; // 调用输入法框架的getInputMethodAbility方法获取实例,并由此实例调用输入法框架功能接口 const inputMethodAbility: inputMethodEngine.InputMethodAbility = inputMethodEngine.getInputMethodAbility(); @@ -95,13 +95,13 @@ public onCreate(context: InputMethodExtensionContext): void { this.mContext = context; - this.initWindow(); // 初始化窗口 - this.registerListener(); // 注册对输入法框架的事件监听 + this.initWindow(); // 初始化窗口 + this.registerListener(); // 注册对输入法框架的事件监听 } - public onDestroy(): void // 应用生命周期销毁 + public onDestroy(): void // 应用生命周期销毁 { - this.unRegisterListener(); // 去注册事件监听 + this.unRegisterListener(); // 去注册事件监听 if(this.panel) { // 销毁窗口 this.panel.hide(); inputMethodAbility.destroyPanel(this.panel); @@ -123,7 +123,7 @@ } } - private initWindow(): void // 初始化窗口 + private initWindow(): void // 初始化窗口 { if(this.mContext === undefined) { return; @@ -150,18 +150,18 @@ private registerListener(): void { - this.registerInputListener(); // 注册对输入法框架服务的监听 + this.registerInputListener(); // 注册对输入法框架服务的监听 ... // 注册隐藏键盘事件监听等 } - private registerInputListener(): void { // 注册对输入法框架服务的开启及停止事件监听 + private registerInputListener(): void { // 注册对输入法框架服务的开启及停止事件监听 inputMethodAbility.on('inputStart', (kbController, textInputClient) => { - this.textInputClient = textInputClient; // 此为输入法客户端实例,由此调用输入法框架提供给输入法应用的功能接口 - this.boardController = kbController; + this.textInputClient = textInputClient; // 此为输入法客户端实例,由此调用输入法框架提供给输入法应用的功能接口 + this.keyboardController = kbController; }) inputMethodAbility.on('inputStop', () => { - this.onDestroy(); // 销毁KeyboardController + this.onDestroy(); // 销毁KeyboardController }); } @@ -232,7 +232,7 @@ @Component struct keyItem { - private keyValue: sourceListType + private keyValue: sourceListType = numberSourceListData[0]; @State keyBgc: string = "#fff" @State keyFontColor: string = "#000" @@ -283,9 +283,9 @@ build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceEvenly }) { Flex({ justifyContent: FlexAlign.SpaceBetween }) { - ForEach(this.numberList, (item: sourceListType) => { // 数字键盘第一行 + ForEach(this.numberList, (item: sourceListType) => { // 数字键盘第一行 keyItem({ keyValue: item }) - }, (item: sourceListType): sourceListType => item.content); + }, (item: sourceListType) => item.content); } .padding({ top: "2%" }) .width("96%") 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 b8e47f7d035c7efc9b2e25c193689c9a4709210e..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) => { @@ -256,44 +258,47 @@ IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信, connectId = this.context.connectServiceExtensionAbility(want,connect); - // 跨设备绑定 - // 第一个参数是本应用的包名,第二个参数是接收deviceManager的回调函数 - deviceManager.createDeviceManager("ohos.rpc.test", (err: Error, data: deviceManager.DeviceManager) => { - if (err) { + // 跨设备绑定 + let deviceManagerCallback = (err: BusinessError, data: deviceManager.DeviceManager) => { + if (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + return; + } + console.info("createDeviceManager success"); + 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); - return; - } - console.info("createDeviceManager success"); - let dmInstance = data; - }); - - // 使用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); - - connectId = this.context.connectServiceExtensionAbility(want,connect); - ``` + } + // 使用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); + } + ``` 3. 服务端处理客户端请求 服务端被绑定的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/database/data-sync-of-rdb-store.md b/zh-cn/application-dev/database/data-sync-of-rdb-store.md index 6a9a67714174a2ffecd4927fcd09bcdfeb1e4363..fcf5a83f0dd4787c1f773596746135b5c1fdde78 100644 --- a/zh-cn/application-dev/database/data-sync-of-rdb-store.md +++ b/zh-cn/application-dev/database/data-sync-of-rdb-store.md @@ -177,6 +177,6 @@ - [分布式组网认证(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedAuthentication) --[分布式关系型数据库(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedRdb) +- [分布式关系型数据库(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedRdb) - [分布式帐号(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedAccount) \ No newline at end of file diff --git a/zh-cn/application-dev/device/stationary-guidelines.md b/zh-cn/application-dev/device/stationary-guidelines.md index 2cce3c90983779331f1e4ae27ac7a5bdb64b3dfa..80b3f018ce0a83a0e62da1735f170c400453232f 100644 --- a/zh-cn/application-dev/device/stationary-guidelines.md +++ b/zh-cn/application-dev/device/stationary-guidelines.md @@ -45,40 +45,46 @@ 1. 订阅绝对静止的进入事件,1秒上报一次。 - ```js + ```ts import stationary from '@ohos.stationary'; - var reportLatencyNs = 1000000000; + import { BusinessError } from '@ohos.base'; + let reportLatencyNs = 1000000000; try { stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { console.log('data='+ JSON.stringify(data)); }) - } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } catch (error) { + let message = (error as BusinessError).message; + console.error('stationary on failed:' + message); } ``` 2. 查询绝对静止状态的进入事件。 - ```js + ```ts import stationary from '@ohos.stationary'; + import { BusinessError } from '@ohos.base'; try { stationary.once('still', (data) => { console.log('data='+ JSON.stringify(data)); }) - } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } catch (error) { + let message = (error as BusinessError).message; + console.error('stationary once failed:' + message); } ``` 3. 取消订阅绝对静止状态的进入事件。 - ```js + ```ts import stationary from '@ohos.stationary'; + import { BusinessError } from '@ohos.base'; try { stationary.off('still', stationary.ActivityEvent.ENTER, (data) => { console.log('data='+ JSON.stringify(data)); }) - } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } catch (error) { + let message = (error as BusinessError).message; + console.error('stationary off failed:' + message); } ``` diff --git a/zh-cn/application-dev/dfx/hitracechain-guidelines.md b/zh-cn/application-dev/dfx/hitracechain-guidelines.md index 71c98626619fb52c6e90b1ed3680077c59ffacbc..4736b8e9d1d2a67429cd523149705c8be7dda688 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/file-management/photoAccessHelper-notify-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md index a6568e442d847946af56ba3a189f0010c391569c..0a5f460ae3da0b97024ebd4d1cfe5986912c0a4c 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md @@ -33,29 +33,27 @@ photoAccessHelper提供监听媒体资源变更的接口,供开发者对指定 ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - - let onCallback = (changeData:dataSharePredicates.ChangeData) => { - console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + let onCallback = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(fileAsset.uri, false, onCallback); + await fileAsset.setFavorite(true); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); } - phAccessHelper.registerChange(fileAsset.uri, false, onCallback); - - await fileAsset.favorite(true); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); } ``` @@ -78,31 +76,31 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, 'albumName'); -let fetchOptions: dataSharePredicates.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfullyfully, albumName: ' + album.albumUri); - - let onCallback = (changeData: photoAccessHelper.ChangeData) => { - console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, 'albumName'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfullyfully, albumName: ' + album.albumUri); + + let onCallback = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(album.albumUri, false, onCallback); + album.albumName = 'newAlbumName' + Date.now(); + await album.commitModify(); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); } - phAccessHelper.registerChange(album.albumUri, false, onCallback); - - album.albumName = 'newAlbumName' + Date.now(); - await album.commitModify(); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); } ``` @@ -129,27 +127,26 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let onCallback = (changeData: dataSharePredicates.ChangeData) => { - console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); -} -phAccessHelper.registerChange(photoAccessHelper.DefaultChangeUri.DEFAULT_PHOTO_URI, true, onCallback); - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - await fileAsset.favorite(true); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); +async function example() { + let onCallback = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(photoAccessHelper.DefaultChangeUri.DEFAULT_PHOTO_URI, true, onCallback); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + await fileAsset.setFavorite(true); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); + } } ``` @@ -172,33 +169,31 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - - let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { - console.info('onCallback1, changData: ' + JSON.stringify(changeData)); - } - let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { - console.info('onCallback2, changData: ' + JSON.stringify(changeData)); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback1, changData: ' + JSON.stringify(changeData)); + } + let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback2, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(fileAsset.uri, false, onCallback1); + phAccessHelper.registerChange(fileAsset.uri, false, onCallback2); + phAccessHelper.unRegisterChange(fileAsset.uri, onCallback1); + await fileAsset.setFavorite(true); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); } - phAccessHelper.registerChange(fileAsset.uri, false, onCallback1); - phAccessHelper.registerChange(fileAsset.uri, false, onCallback2); - phAccessHelper.unRegisterChange(fileAsset.uri, onCallback1); - - await fileAsset.favorite(true); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); } ``` diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-overview.md b/zh-cn/application-dev/file-management/photoAccessHelper-overview.md index 9ac3deb5f0c76597d9e78415669c40e7d0168bb1..6546d5c56a92465e6eca08704850ed3ea4297032 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-overview.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-overview.md @@ -107,14 +107,12 @@ let phAccessHelper: photoAccessHelper.PhotoAccessHelper = photoAccessHelper.getP export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { let list : Array = ['ohos.permission.READ_IMAGEVIDEO', 'ohos.permission.WRITE_IMAGEVIDEO']; - let permissionRequestResult; let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(this.context, list, (err, result) => { if (err) { console.error('requestPermissionsFromUserError: ' + JSON.stringify(err)); } else { - permissionRequestResult = result; - console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); + console.info('permissionRequestResult: ' + JSON.stringify(result)); } }); } diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md index a728ea8e283eebd21343551c0030731692ec5069..68c21f740e2a7d18e48da3a56dcf66f06183a7e5 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md @@ -27,34 +27,24 @@ 下面以查询文件名为'test.jpg'的图片资源为例。 -**开发步骤:** - -创建FetchOptions对象指定检索条件为检索文件名为'test.jpg'的图片。 - ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; -``` -调用PhotoAccessHelper.getAssets接口获取图片资源。 - -```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - fetchResult.close(); -} catch (err) { - console.error('getAssets failed with err: ' + err); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + fetchResult.close(); + } catch (err) { + console.error('getAssets failed with err: ' + err); + } } ``` @@ -64,65 +54,53 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.PhotoKeys.URI, 'file://media/Photo/1'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; -``` -调用PhotoAccessHelper.getAssets接口获取图片资源。 +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.URI, 'file://media/Photo/1'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; -```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - fetchResult.close(); -} catch (err) { - console.error('getAssets failed with err: ' + err); + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + fetchResult.close(); + } catch (err) { + console.error('getAssets failed with err: ' + err); + } } ``` - ### 指定文件添加的时间获取图片或视频资源 下面以查询指定添加时间为'2022-06-01'至'2023-06-01'这一年内为例。 ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let startTime: Number = Date.parse(new Date('2022-06-01').toString()) / 1000; // The value of the start time is the number of seconds elapsed since the Epoch time. -let endTime: Number = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time. -let date_added: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.DATE_ADDED; -predicates.between(date_added, startTime, endTime); -predicates.orderByDesc(date_added); // Sort the obtained records in descending order. -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [date_added], // The date_added attribute is not a default option and needs to be added. - predicates: predicates -}; -``` - -调用PhotoAccessHelper.getAssets接口获取图片资源。 -```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - console.info('getAssets count: ' + fetchResult.getCount()); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - fetchResult.close(); -} catch (err) { - console.error('getAssets failed with err: ' + err); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // 查询起始时间距1970年1月1日的秒数值。 + let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // 查询结束时间距1970年1月1日的秒数值。 + let date_added: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.DATE_ADDED; + predicates.between(date_added, startTime, endTime); + predicates.orderByDesc(date_added); // 查询结果按照降序排序。 + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [date_added], // date_added属性不属于默认查询列,需要自行添加。 + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + console.info('getAssets count: ' + fetchResult.getCount()); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + fetchResult.close(); + } catch (err) { + console.error('getAssets failed with err: ' + err); + } } ``` @@ -151,26 +129,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; import image from '@ohos.multimedia.image'; -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - let size: image.Size = { width: 720, height: 720 }; - let pixelMap: image.PixelMap = await fileAsset.getThumbnail(size); - let imageInfo: image.ImageInfo = await pixelMap.getImageInfo() - console.info('getThumbnail successful, pixelMap ImageInfo size: ' + JSON.stringify(imageInfo.size)); - fetchResult.close(); -} catch (err) { - console.error('getThumbnail failed with err: ' + err); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + let size: image.Size = { width: 720, height: 720 }; + let pixelMap: image.PixelMap = await fileAsset.getThumbnail(size); + let imageInfo: image.ImageInfo = await pixelMap.getImageInfo() + console.info('getThumbnail successful, pixelMap ImageInfo size: ' + JSON.stringify(imageInfo.size)); + fetchResult.close(); + } catch (err) { + console.error('getThumbnail failed with err: ' + err); + } } ``` @@ -193,18 +172,18 @@ try { 2. 调用createAsset接口创建图片资源。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let displayName: string = 'testPhoto' + Date.now() + '.jpg'; - let createOption: photoAccessHelper.CreateOptions = { - subType: photoAccessHelper.PhotoSubtype.DEFAULT - }; - - let fileAsset: photoAccessHelper.photoAsset = await phAccessHelper.createAsset(displayName, createOption); - console.info('createAsset successfully, file displayName: ' + fileAsset.displayName); -} catch (err) { - console.error('createAsset failed, message = ', err); +async function example() { + try { + let displayName: string = 'testPhoto' + Date.now() + '.jpg'; + let createOption: photoAccessHelper.PhotoCreateOptions = { + subtype: photoAccessHelper.PhotoSubtype.DEFAULT + }; + + let fileAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(displayName, createOption); + console.info('createAsset successfully, file displayName: ' + fileAsset.displayName); + } catch (err) { + console.error('createAsset failed, message = ', err); + } } ``` @@ -233,26 +212,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: ['title'], - predicates: predicates -}; -let newTitle = 'newTestPhoto'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE; - let fileAssetTitle: photoAccessHelper.MemberType = fileAsset.get(title); - console.info('getAssets fileAsset.title : ' + fileAssetTitle); - fileAsset.set(title, newTitle); - await fileAsset.commitModify(); - fetchResult.close(); -} catch (err) { - console.error('commitModify failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: ['title'], + predicates: predicates + }; + let newTitle = 'newTestPhoto'; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE; + let fileAssetTitle: photoAccessHelper.MemberType = fileAsset.get(title); + console.info('getAssets fileAsset.title : ' + fileAssetTitle); + fileAsset.set(title, newTitle); + await fileAsset.commitModify(); + fetchResult.close(); + } catch (err) { + console.error('commitModify failed with err: ' + err); + } } ``` @@ -278,21 +258,22 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - await phAccessHelper.deleteAssets([fileAsset.uri]); - fetchResult.close(); -} catch (err) { - console.error('deleteAssets failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + await phAccessHelper.deleteAssets([fileAsset.uri]); + fetchResult.close(); + } catch (err) { + console.error('deleteAssets failed with err: ' + err); + } } ``` diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md index 11fdee073158b8bddb39d5c8736ef63cad4e37a1..18c3c2b7352d1a48066316be58f7244955a68acb 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md @@ -29,15 +29,15 @@ photoAccessHelper仅提供开发者对收藏夹、视频相册、截屏和录屏 2. 调用getAlbums接口获取收藏夹对象。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - fetchResult.close(); -} catch (err) { - console.error('get favorite Album failed with err: ' + err); +async function example() { + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); + } catch (err) { + console.error('get favorite Album failed with err: ' + err); + } } ``` @@ -60,23 +60,24 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - let favoriteState = true; - await fileAsset.setFavorite(favoriteState); -} catch (err) { - console.error('setFavorite failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + let favoriteState = true; + await fileAsset.setFavorite(favoriteState); + } catch (err) { + console.error('setFavorite failed with err: ' + err); + } } ``` @@ -100,26 +101,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - - let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); - photoFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('favorite failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); + photoFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('favorite failed with err: ' + err); + } } ``` @@ -143,28 +145,29 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - - let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); - let favoriteState = false; - await fileAsset.setFavorite(favoriteState); - photoFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('setFavorite failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); + let favoriteState = false; + await fileAsset.setFavorite(favoriteState); + photoFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('setFavorite failed with err: ' + err); + } } ``` @@ -187,15 +190,15 @@ try { 2. 调用getAlbums接口获取视频相册。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('get video Album successfully, albumUri: ' + album.albumUri); - fetchResult.close(); -} catch (err) { - console.error('get video Album failed with err: ' + err); +async function example() { + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('get video Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); + } catch (err) { + console.error('get video Album failed with err: ' + err); + } } ``` @@ -219,26 +222,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get video Album successfully, albumUri: ' + album.albumUri); - - let videoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await videoFetchResult.getFirstObject(); - console.info('video album getAssets successfully, albumName: ' + fileAsset.displayName); - videoFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('video failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get video Album successfully, albumUri: ' + album.albumUri); + + let videoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await videoFetchResult.getFirstObject(); + console.info('video album getAssets successfully, albumName: ' + fileAsset.displayName); + videoFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('video failed with err: ' + err); + } } ``` @@ -261,15 +265,15 @@ try { 2. 调用getAlbums接口获取截屏和录屏相册。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('get screenshot Album successfully, albumUri: ' + album.albumUri); - fetchResult.close(); -} catch (err) { - console.error('get screenshot Album failed with err: ' + err); +async function example() { + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('get screenshot Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); + } catch (err) { + console.error('get screenshot Album failed with err: ' + err); + } } ``` @@ -293,25 +297,26 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get screenshot album successfully, albumUri: ' + album.albumUri); - - let screenshotFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await screenshotFetchResult.getFirstObject(); - console.info('screenshot album getAssets successfully, albumName: ' + fileAsset.displayName); - screenshotFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('screenshot album failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get screenshot album successfully, albumUri: ' + album.albumUri); + + let screenshotFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await screenshotFetchResult.getFirstObject(); + console.info('screenshot album getAssets successfully, albumName: ' + fileAsset.displayName); + screenshotFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('screenshot album failed with err: ' + err); + } } ``` diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md index 4ab3997cb988e3e05895c8b4c79595e307d940b4..5206f5cde46589440d7577c93439b30b9c583b5d 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md @@ -34,14 +34,14 @@ photoAccessHelper提供用户相册相关的接口,供开发者创建、删除 2. 调用createAlbum接口创建相册。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let albumName = 'albumName'; - let album: photoAccessHelper.Album = await phAccessHelper.createAlbum(albumName); - console.info('createAlbum successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); -} catch (err) { - console.error('createAlbum failed with err: ' + err); +async function example() { + try { + let albumName = 'albumName'; + let album: photoAccessHelper.Album = await phAccessHelper.createAlbum(albumName); + console.info('createAlbum successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); + } catch (err) { + console.error('createAlbum failed with err: ' + err); + } } ``` @@ -64,23 +64,24 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, 'albumName'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - fetchResult.close(); -} catch (err) { - console.error('getAlbums failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, 'albumName'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + fetchResult.close(); + } catch (err) { + console.error('getAlbums failed with err: ' + err); + } } ``` @@ -111,25 +112,26 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, 'albumName'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - album.albumName = 'newAlbumName'; - await album.commitModify(); - fetchResult.close(); -} catch (err) { - console.error('commitModify failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, 'albumName'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + album.albumName = 'newAlbumName'; + await album.commitModify(); + fetchResult.close(); + } catch (err) { + console.error('commitModify failed with err: ' + err); + } } ``` @@ -156,34 +158,35 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: dataSharePredicates.FetchOptions = { - fetchColumns: [], - predicates: albumPredicates -}; - -let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: photoPredicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(photoFetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('getAssets successfully, albumName: ' + fileAsset.displayName); - await album.addAssets([fileAsset]); - albumFetchResult.close(); - photoFetchResult.close(); -} catch (err) { - console.error('addAssets failed with err: ' + err); + +async function example() { + let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + albumPredicates.equalTo(albumName, 'albumName'); + let albumFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: albumPredicates + }; + + let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let photoFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: photoPredicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(photoFetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('getAssets successfully, albumName: ' + fileAsset.displayName); + await album.addAssets([fileAsset]); + albumFetchResult.close(); + photoFetchResult.close(); + } catch (err) { + console.error('addAssets failed with err: ' + err); + } } ``` @@ -209,33 +212,34 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; -albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: albumPredicates -}; - -let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: photoPredicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult = await album.getAssets(photoFetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); - console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); - albumFetchResult.close(); - photoFetchResult.close(); -} catch (err) { - console.error('album getAssets failed with err: ' + err); + +async function example() { + let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + albumPredicates.equalTo(albumName, 'albumName'); + let albumFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: albumPredicates + }; + + let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let photoFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: photoPredicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult = await album.getAssets(photoFetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); + albumFetchResult.close(); + photoFetchResult.close(); + } catch (err) { + console.error('album getAssets failed with err: ' + err); + } } ``` @@ -264,34 +268,35 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: albumPredicates -}; - -let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: photoPredicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult = await album.getAssets(photoFetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); - console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); - await album.removeAssets([fileAsset]); - albumFetchResult.close(); - photoFetchResult.close(); -} catch (err) { - console.error('removeAssets failed with err: ' + err); + +async function example() { + let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + albumPredicates.equalTo(albumName, 'albumName'); + let albumFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: albumPredicates + }; + + let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let photoFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: photoPredicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult = await album.getAssets(photoFetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); + await album.removeAssets([fileAsset]); + albumFetchResult.close(); + photoFetchResult.close(); + } catch (err) { + console.error('removeAssets failed with err: ' + err); + } } ``` @@ -315,23 +320,24 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, '%albumName%'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - phAccessHelper.deleteAlbums([album]); - fetchResult.close(); -} catch (err) { - console.error('deleteAlbums failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, '%albumName%'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + phAccessHelper.deleteAlbums([album]); + fetchResult.close(); + } catch (err) { + console.error('deleteAlbums failed with err: ' + err); + } } ``` diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md b/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md index 8823fbbb79e5a8bb54d2fb072be38f9e14f376a7..695c83f936f3c63fe0b357323f3153bacce3bf22 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md @@ -96,6 +96,7 @@ launchType字段配置为specified时,系统会根据AbilityStage的onAcceptWa // MyAbilityStage.ts import AbilityStage from "@ohos.app.ability.AbilityStage" import deviceInfo from'@ohos.deviceInfo' +import Want from '@ohos.app.ability.Want' export default class MyAbilityStage extends AbilityStage { ... @@ -107,7 +108,7 @@ export default class MyAbilityStage extends AbilityStage { // 如果不是平板,直接以设备类型作为key,每次启动的key相同 return deviceInfo.deviceType } - onAcceptWant(want) { + onAcceptWant(want: Want) : string{ return this.generateKey() } } diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md index 83b16dfed29cad6e202ea40175a4136bcdec5fe7..6da55b1e785e4a4db3c69a7e2047c433ac434609 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md @@ -52,15 +52,16 @@ ```ts // MainAbility.ts - import window from '@ohos.window' + import type window from '@ohos.window' import display from '@ohos.display' + import Ability from '@ohos.app.ability.Ability' export default class MainAbility extends Ability { private windowObj: window.Window private curBp: string - ... + //... // 根据当前窗口尺寸更新断点 - private updateBreakpoint(windowWidth) { + private updateBreakpoint(windowWidth) :void{ // 将长度的单位由px换算为vp let windowWidthVp = windowWidth / (display.getDefaultDisplaySync().densityDPI / 160) let newBp: string = '' @@ -80,7 +81,7 @@ } } - onWindowStageCreate(windowStage: window.WindowStage) { + onWindowStageCreate(windowStage: window.WindowStage) :void{ windowStage.getMainWindow().then((windowObj) => { this.windowObj = windowObj // 获取应用启动时的窗口尺寸 @@ -90,16 +91,16 @@ this.updateBreakpoint(windowSize.width) }) }); - ... + // ... } // 窗口销毁时,取消窗口尺寸变化监听 - onWindowStageDestroy() { + onWindowStageDestroy() :void{ if (this.windowObj) { this.windowObj.off('windowSizeChange') } } - ... + //... } ``` @@ -165,7 +166,7 @@ export class BreakpointType { this.md = md this.lg = lg } - GetValue(currentBreakpoint: string) { + GetValue(currentBreakpoint: string):T { if (currentBreakpoint === 'sm') { return this.sm } @@ -185,29 +186,29 @@ export class BreakpointSystem { private mdListener: mediaquery.MediaQueryListener private lgListener: mediaquery.MediaQueryListener - private updateCurrentBreakpoint(breakpoint: string) { + private updateCurrentBreakpoint(breakpoint: string) :void{ if (this.currentBreakpoint !== breakpoint) { this.currentBreakpoint = breakpoint AppStorage.Set('currentBreakpoint', this.currentBreakpoint) } } - private isBreakpointSM = (mediaQueryResult) => { + private isBreakpointSM = (mediaQueryResult:mediaquery.MediaQueryResult) :void=> { if (mediaQueryResult.matches) { this.updateCurrentBreakpoint('sm') } } - private isBreakpointMD = (mediaQueryResult) => { + private isBreakpointMD = (mediaQueryResult:mediaquery.MediaQueryResult) :void=> { if (mediaQueryResult.matches) { this.updateCurrentBreakpoint('md') } } - private isBreakpointLG = (mediaQueryResult) => { + private isBreakpointLG = (mediaQueryResult:mediaquery.MediaQueryResult):void => { if (mediaQueryResult.matches) { this.updateCurrentBreakpoint('lg') } } - public register() { + public register() :void{ this.smListener = mediaquery.matchMediaSync("(320vp{ + ForEach(this.bgColors, (bgColor:ResourceColor)=>{ GridCol({span: {sm: 2, md: 2, lg: 2}}) { Row().backgroundColor(bgColor).height(30).width('100%') } @@ -538,21 +539,25 @@ struct GridRowSample4 { ```ts +class Obj { + public index: number = 1; + public color: Resource = $r('sys.color.ohos_id_color_palette_aux1') +} @Entry @Component struct GridRowSample5 { - private elements: Object[] = [ - {'index': 1, 'color': $r('sys.color.ohos_id_color_palette_aux1')}, - {'index': 2, 'color': $r('sys.color.ohos_id_color_palette_aux2')}, - {'index': 3, 'color': $r('sys.color.ohos_id_color_palette_aux3')}, - {'index': 4, 'color': $r('sys.color.ohos_id_color_palette_aux4')}, - {'index': 5, 'color': $r('sys.color.ohos_id_color_palette_aux5')}, - {'index': 6, 'color': $r('sys.color.ohos_id_color_palette_aux6')}, + private elements: Obj[] = [ + {index: 1, color: $r('sys.color.ohos_id_color_palette_aux1')}, + {index: 2, color: $r('sys.color.ohos_id_color_palette_aux2')}, + {index: 3, color: $r('sys.color.ohos_id_color_palette_aux3')}, + {index: 4, color: $r('sys.color.ohos_id_color_palette_aux4')}, + {index: 5, color: $r('sys.color.ohos_id_color_palette_aux5')}, + {index: 6, color: $r('sys.color.ohos_id_color_palette_aux6')}, ] build() { GridRow() { - ForEach(this.elements, (item)=>{ + ForEach(this.elements, (item:Obj)=>{ GridCol({span: {sm: 6, md: (item.index % 3 === 0) ? 0 : 4, lg: 3}}) { Row() { Text('' + item.index).fontSize(24) @@ -580,21 +585,25 @@ struct GridRowSample5 { ```ts +class Obj { + public index: number = 1; + public color: Resource = $r('sys.color.ohos_id_color_palette_aux1') +} @Entry @Component struct GridRowSample6 { - private elements: Object[] = [ - {'index': 1, 'color': $r('sys.color.ohos_id_color_palette_aux1')}, - {'index': 2, 'color': $r('sys.color.ohos_id_color_palette_aux2')}, - {'index': 3, 'color': $r('sys.color.ohos_id_color_palette_aux3')}, - {'index': 4, 'color': $r('sys.color.ohos_id_color_palette_aux4')}, - {'index': 5, 'color': $r('sys.color.ohos_id_color_palette_aux5')}, - {'index': 6, 'color': $r('sys.color.ohos_id_color_palette_aux6')}, + private elements: Obj[] = [ + {index: 1, color: $r('sys.color.ohos_id_color_palette_aux1')}, + {index: 2, color: $r('sys.color.ohos_id_color_palette_aux2')}, + {index: 3, color: $r('sys.color.ohos_id_color_palette_aux3')}, + {index: 4, color: $r('sys.color.ohos_id_color_palette_aux4')}, + {index: 5, color: $r('sys.color.ohos_id_color_palette_aux5')}, + {index: 6, color: $r('sys.color.ohos_id_color_palette_aux6')}, ] build() { GridRow() { - ForEach(this.elements, (item)=>{ + ForEach(this.elements, (item:Obj)=>{ GridCol({span: {sm: 6, md: 4, lg: 3}, offset: {sm: 0, md: 2, lg: 1} }) { Row() { Text('' + item.index).fontSize(24) @@ -622,21 +631,25 @@ struct GridRowSample6 { ```ts +class Obj { + public index: number = 1; + public color: Resource = $r('sys.color.ohos_id_color_palette_aux1') +} @Entry @Component struct GridRowSample7 { - private elements: Object[] = [ - {'index': 1, 'color': $r('sys.color.ohos_id_color_palette_aux1')}, - {'index': 2, 'color': $r('sys.color.ohos_id_color_palette_aux2')}, - {'index': 3, 'color': $r('sys.color.ohos_id_color_palette_aux3')}, - {'index': 4, 'color': $r('sys.color.ohos_id_color_palette_aux4')}, - {'index': 5, 'color': $r('sys.color.ohos_id_color_palette_aux5')}, - {'index': 6, 'color': $r('sys.color.ohos_id_color_palette_aux6')}, + private elements: Obj[] = [ + {index: 1, color: $r('sys.color.ohos_id_color_palette_aux1')}, + {index: 2, color: $r('sys.color.ohos_id_color_palette_aux2')}, + {index: 3, color: $r('sys.color.ohos_id_color_palette_aux3')}, + {index: 4, color: $r('sys.color.ohos_id_color_palette_aux4')}, + {index: 5, color: $r('sys.color.ohos_id_color_palette_aux5')}, + {index: 6, color: $r('sys.color.ohos_id_color_palette_aux6')}, ] build() { GridRow() { - ForEach(this.elements, (item)=>{ + ForEach(this.elements, (item:Obj)=>{ GridCol({span: {sm: 6, md: 4, lg: 3}, order: {lg: (6-item.index)}}) { Row() { Text('' + item.index).fontSize(24) @@ -664,21 +677,24 @@ struct GridRowSample7 { ```ts +class Obj { + public index: number = 1; + public color: Resource = $r('sys.color.ohos_id_color_palette_aux1') +} @Entry @Component struct GridRowSample8 { - private elements: Object[] = [ - {'index': 1, 'color': $r('sys.color.ohos_id_color_palette_aux1')}, - {'index': 2, 'color': $r('sys.color.ohos_id_color_palette_aux2')}, - {'index': 3, 'color': $r('sys.color.ohos_id_color_palette_aux3')}, - {'index': 4, 'color': $r('sys.color.ohos_id_color_palette_aux4')}, - {'index': 5, 'color': $r('sys.color.ohos_id_color_palette_aux5')}, - {'index': 6, 'color': $r('sys.color.ohos_id_color_palette_aux6')}, + private elements: Obj[] = [ + {index: 1, color: $r('sys.color.ohos_id_color_palette_aux1')}, + {index: 2, color: $r('sys.color.ohos_id_color_palette_aux2')}, + {index: 3, color: $r('sys.color.ohos_id_color_palette_aux3')}, + {index: 4, color: $r('sys.color.ohos_id_color_palette_aux4')}, + {index: 5, color: $r('sys.color.ohos_id_color_palette_aux5')}, + {index: 6, color: $r('sys.color.ohos_id_color_palette_aux6')}, ] - build() { GridRow() { - ForEach(this.elements, (item)=>{ + ForEach(this.elements, (item:Obj)=>{ // 不配置md断点下三个参数的值,则其取值与sm断点相同 GridCol({span: {sm:4, lg: 3}, offset: {sm: 2, lg: 1}, order: {sm: (6-item.index), lg: item.index}}) { @@ -707,23 +723,26 @@ struct GridRowSample8 { ```ts +class Obj { + public index: number = 1; + public color: Resource = $r('sys.color.ohos_id_color_palette_aux1') +} @Entry @Component struct GridRowSample9 { - private elements: Object[] = [ - {'index': 1, 'color': $r('sys.color.ohos_id_color_palette_aux1')}, - {'index': 2, 'color': $r('sys.color.ohos_id_color_palette_aux2')}, - {'index': 3, 'color': $r('sys.color.ohos_id_color_palette_aux3')}, - {'index': 4, 'color': $r('sys.color.ohos_id_color_palette_aux4')}, - {'index': 5, 'color': $r('sys.color.ohos_id_color_palette_aux5')}, - {'index': 6, 'color': $r('sys.color.ohos_id_color_palette_aux6')}, + private elements: Obj[] = [ + {index: 1, color: $r('sys.color.ohos_id_color_palette_aux1')}, + {index: 2, color: $r('sys.color.ohos_id_color_palette_aux2')}, + {index: 3, color: $r('sys.color.ohos_id_color_palette_aux3')}, + {index: 4, color: $r('sys.color.ohos_id_color_palette_aux4')}, + {index: 5, color: $r('sys.color.ohos_id_color_palette_aux5')}, + {index: 6, color: $r('sys.color.ohos_id_color_palette_aux6')}, ] - build() { GridRow() { GridCol({span: {sm: 12, md: 10, lg: 8}, offset: {sm: 0, md: 1, lg: 2}}) { GridRow() { - ForEach(this.elements, (item)=>{ + ForEach(this.elements, (item:Obj)=>{ GridCol({span: {sm: 6, md: 4, lg: 3}}) { Row() { Text('' + item.index).fontSize(24) diff --git a/zh-cn/application-dev/media/audio-effect-management.md b/zh-cn/application-dev/media/audio-effect-management.md index 414fb2aa9f7936a9ef8bedbb2698fd1bb0879f61..1f28fa95e80e1336a3e7550890aba9639043d7e0 100644 --- a/zh-cn/application-dev/media/audio-effect-management.md +++ b/zh-cn/application-dev/media/audio-effect-management.md @@ -6,52 +6,55 @@ 主要包括查询和设置当前音频播放流的音效模式,音效模式包括EFFECT_NONE关闭音效模式和EFFECT_DEFAULT默认音效模式。默认音效模式会根据创建音频流的ContentType和StreamUsage自动加载对应场景的音效。 -### 获取播放实例(示例代码仅支持JS格式) +### 获取播放实例 管理播放实例音效的接口是getAudioEffectMode()查询当前音频播放流的音效模式和setAudioEffectMode(mode: AudioEffectMode)设置当前音频播放流的音效模式,在使用之前,需要使用createAudioRenderer(options: AudioRendererOptions)先创建音频播放流AudioRenderer实例。 1. 步骤一:导入音频接口。 - ```js + ```ts import audio from '@ohos.multimedia.audio'; ``` 2. 步骤二:配置音频渲染参数并创建AudioRenderer实例,音频渲染参数的详细信息可以查看[AudioRendererOptions](../reference/apis/js-apis-audio.md#audiorendereroptions8),创建AudioRenderer实例时会默认挂载EFFECT_DEFAULT模式音效。 - ```js - let audioStreamInfo = { + ```ts + import audio from '@ohos.multimedia.audio'; + import { BusinessError } from '@ohos.base'; + let audioStreamInfo: audio.AudioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW }; - let audioRendererInfo = { + let audioRendererInfo: audio.AudioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, rendererFlags: 0 }; - let audioRendererOptions = { + let audioRendererOptions: audio.AudioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo }; - audio.createAudioRenderer(audioRendererOptions, (err, data) => { + audio.createAudioRenderer(audioRendererOptions, (err: BusinessError, data: audio.AudioRenderer) => { if (err) { console.error(`Invoke createAudioRenderer failed, code is ${err.code}, message is ${err.message}`); return; } else { console.info('Invoke createAudioRenderer succeeded.'); - let audioRenderer = data; + let audioRenderer: audio.AudioRenderer = data; } }); ``` -### 查询当前播放实例的音效模式(示例代码仅支持JS格式) +### 查询当前播放实例的音效模式 - ```js - audioRenderer.getAudioEffectMode((err, effectmode) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioRenderer.getAudioEffectMode((err: BusinessError, effectmode: audio.AudioEffectMode) => { if (err) { console.error(`Failed to get params, code is ${err.code}, message is ${err.message}`); return; @@ -61,12 +64,13 @@ }); ``` -### 设置当前播放实例的音效模式(示例代码仅支持JS格式) +### 设置当前播放实例的音效模式 关闭系统音效: - ```js - audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_NONE, (err) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_NONE, (err: BusinessError) => { if (err) { console.error(`Failed to set params, code is ${err.code}, message is ${err.message}`); return; @@ -78,8 +82,9 @@ 开启系统音效默认模式: - ```js - audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT, (err) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT, (err: BusinessError) => { if (err) { console.error(`Failed to set params, code is ${err.code}, message is ${err.message}`); return; @@ -94,20 +99,21 @@ 主要包括全局音效查询相应StreamUsage对应场景的音效模式。 对于播放音频类的应用,开发者需要关注该应用的音频流使用什么音效模式并做出相应的操作,比如音乐App播放时,应选择音乐场景下的模式。在使用查询接口前,开发者需要使用getStreamManager()创建一个AudioStreamManager音频流管理实例。 -### 获取音频流管理接口(示例代码仅支持JS格式) +### 获取音频流管理接口 1.创建AudioStreamManager实例。在使用AudioStreamManager的API前,需要使用getStreamManager()创建一个AudioStreamManager实例。 - ```js + ```ts import audio from '@ohos.multimedia.audio'; let audioManager = audio.getAudioManager(); let audioStreamManager = audioManager.getStreamManager(); ``` -### 查询对应场景的音效模式(示例代码仅支持JS格式) +### 查询对应场景的音效模式 - ```js - audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MEDIA, async (err, audioEffectInfoArray) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MEDIA, async (err: BusinessError, audioEffectInfoArray: audio.AudioEffectInfoArray) => { if (err) { console.error('Failed to get effect info array'); return; diff --git a/zh-cn/application-dev/media/dual-channel-preview.md b/zh-cn/application-dev/media/camera-dual-channel-preview.md similarity index 97% rename from zh-cn/application-dev/media/dual-channel-preview.md rename to zh-cn/application-dev/media/camera-dual-channel-preview.md index e5f29744c4d985085075bb1dabdbdd0bed99eeb4..bc37733fd0a32d9a26c31e208b494535fbf014dd 100644 --- a/zh-cn/application-dev/media/dual-channel-preview.md +++ b/zh-cn/application-dev/media/camera-dual-channel-preview.md @@ -11,6 +11,12 @@ - 暂不支持动态添加流,即不能在没有调用session.stop的情况下,调用addOutput添加流。 - 对ImageReceiver组件获取到的图像数据处理后,需要将对应的图像Buffer释放,确保Surface的BufferQueue正常轮转。 +## 调用流程 + +双路方案调用流程图建议如下: + +![dual-preview-streams-instructions](figures/dual-preview-streams-instructions.png) + ## 开发步骤 1. 导入image接口。 diff --git a/zh-cn/application-dev/media/camera-mode.md b/zh-cn/application-dev/media/camera-mode.md index 200a3c830d15c9e72c7d3f11782e86596395d519..099430060bd8162d4626158943180a713efdaa98 100644 --- a/zh-cn/application-dev/media/camera-mode.md +++ b/zh-cn/application-dev/media/camera-mode.md @@ -1,4 +1,4 @@ -# 人像模式拍照实现方案 +# 使用人像模式拍照 ## 开发流程 @@ -178,7 +178,7 @@ async function cameraModeCase(context: featureAbility.Context, surfaceId: string // 获取支持的美颜类型对应的美颜强度范围 let beautyRanges: Array; try { - beautyRanges = portraitSession.getSupportedBeautyRanges(beautyTypes[0]); + beautyRanges = portraitSession.getSupportedBeautyRange(beautyTypes[0]); } catch (error) { let err = error as BusinessError; console.error('Failed to get the beauty types ranges. errorCode = ' + err.code); diff --git a/zh-cn/application-dev/media/camera-performance-improvement.md b/zh-cn/application-dev/media/camera-performance-improvement.md index 2cd4d412cb255e1a4895064cc4014d9ebb120b95..65f21efecf9241c7eb2e07ef3d5b9d39298346ba 100644 --- a/zh-cn/application-dev/media/camera-performance-improvement.md +++ b/zh-cn/application-dev/media/camera-performance-improvement.md @@ -33,7 +33,7 @@ [各类Context的获取方式](../application-models/application-context-stage.md) -```js +```ts import camera from '@ohos.multimedia.camera'; import featureAbility from '@ohos.ability.featureAbility'; @@ -83,7 +83,7 @@ async function preview(context: featureAbility.Context, cameraInfo: camera.Camer ![](figures/quick-thumbnail-sequence-diagram.png) [各类Context的获取方式](../application-models/application-context-stage.md) -```js +```ts import camera from '@ohos.multimedia.camera'; import { BusinessError } from '@ohos.base'; import image from '@ohos.multimedia.image'; @@ -152,7 +152,7 @@ function showOrSavePicture(pixelMap: image.PixelMap): void { - **桌面应用** - ```js + ```ts import camera from '@ohos.multimedia.camera'; import { BusinessError } from '@ohos.base'; import featureAbility from '@ohos.ability.featureAbility'; @@ -174,7 +174,7 @@ function showOrSavePicture(pixelMap: image.PixelMap): void { 具体申请方式及校验方式,请参考[访问控制授权申请指导](../security/accesstoken-guidelines.md)。 - ```js + ```ts import camera from '@ohos.multimedia.camera'; import { BusinessError } from '@ohos.base'; import featureAbility from '@ohos.ability.featureAbility'; diff --git a/zh-cn/application-dev/media/figures/dual-preview-streams-instructions.png b/zh-cn/application-dev/media/figures/dual-preview-streams-instructions.png new file mode 100644 index 0000000000000000000000000000000000000000..9aa278cb9e0834f396f00bc2999ee1c3c737b758 Binary files /dev/null and b/zh-cn/application-dev/media/figures/dual-preview-streams-instructions.png differ 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/napi/drawing-guidelines.md b/zh-cn/application-dev/napi/drawing-guidelines.md index 1a2a473509f039b13a5affe9ecb6847b77fbee81..2c65e7981d4541741d520d10e5547f11b18968d4 100644 --- a/zh-cn/application-dev/napi/drawing-guidelines.md +++ b/zh-cn/application-dev/napi/drawing-guidelines.md @@ -35,7 +35,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ## 2D图形绘制开发步骤 -以下步骤描述了在**OpenHarmony**如何使用 **Native Drawing** 模块的画布画笔绘制一个基本的2D图形: +以下步骤描述了如何使用 **Native Drawing** 模块的画布画笔绘制一个基本的2D图形: 1. **创建Bitmap实例**。使用 **drawing_bitmap.h** 的 **OH_Drawing_BitmapCreate** 接口创建一个Bitmap实例 **cBitmap**,并使用 **OH_Drawing_BitmapBuild** 指定其长宽大小和像素格式。 @@ -137,7 +137,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ## 文本绘制开发步骤 -以下步骤描述了在OpenHarmony中,如何使用**Native Drawing**模块的文字显示功能: +以下步骤描述了如何使用**Native Drawing**模块的文字显示功能: 1. **创建画布和bitmap实例**。 ```c++ diff --git a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md index f0a2a4db4bf4653a1e9cf57f4d775b6aa6e45522..dc189e94acab9d6b5722914bce4b6f4d78145257 100644 --- a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md +++ b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md @@ -265,8 +265,8 @@ int GenerateInputDataWithRandom(OH_AI_TensorHandleArray inputs) { 2. 运行。 - - 使用hdc_std连接rk3568开发板,并将demo和mobilenetv2.ms推送到设备中的相同目录。 - - 使用hdc_std shell进入开发板,并进入demo所在的目录执行如下命令,即可得到结果。 + - 使用hdc_std连接设备,并将demo和mobilenetv2.ms推送到设备中的相同目录。 + - 使用hdc_std shell进入设备,并进入demo所在的目录执行如下命令,即可得到结果。 ```shell ./demo mobilenetv2.ms diff --git a/zh-cn/application-dev/napi/napi-guidelines.md b/zh-cn/application-dev/napi/napi-guidelines.md index 6dbf776e8b068efc3820daf15ae61e4cf8bb1882..1c56a1bb60255eaabc64fc8f6afcec62ff671421 100644 --- a/zh-cn/application-dev/napi/napi-guidelines.md +++ b/zh-cn/application-dev/napi/napi-guidelines.md @@ -139,7 +139,7 @@ struct Index { .fontWeight(FontWeight.Bold) .onClick(() => { hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); - let ret = entry.nativeCallArkTS((value)=>{return value * 2;}); + let ret: number = entry.nativeCallArkTS((value: number)=>{return value * 2;}); hilog.info(0x0000, 'testTag', 'Test NAPI nativeCallArkTS ret = %{public}d', ret); }) } diff --git a/zh-cn/application-dev/napi/native-buffer-guidelines.md b/zh-cn/application-dev/napi/native-buffer-guidelines.md index 59309b082a1f4781240f08eeb21e84ee973bbfd3..7af175b902f6209242112d0e14cc97dfd76398af 100644 --- a/zh-cn/application-dev/napi/native-buffer-guidelines.md +++ b/zh-cn/application-dev/napi/native-buffer-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -NativeBuffer是`OpenHarmony`提供**共享内存**的模块。开发者可以通过`NativeBuffer`接口实现共享内存的申请、使用、属性查询、释放等操作。 +NativeBuffer是提供**共享内存**的模块。开发者可以通过`NativeBuffer`接口实现共享内存的申请、使用、属性查询、释放等操作。 针对NativeBuffer,常见的开发场景如下: * 通过`NativeBuffer`提供的Native API接口申请`OH_NativeBuffer`实例,获取内存的属性信息,把对应的ION内存映射到进程空间。 @@ -23,7 +23,7 @@ NativeBuffer是`OpenHarmony`提供**共享内存**的模块。开发者可以通 ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeBuffer`提供的Native API接口,创建`OH_NativeBuffer`实例获取内存的属性信息,并把对应的ION内存映射到进程空间。 +以下步骤描述了如何使用`NativeBuffer`提供的Native API接口,创建`OH_NativeBuffer`实例获取内存的属性信息,并把对应的ION内存映射到进程空间。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/native-image-guidelines.md b/zh-cn/application-dev/napi/native-image-guidelines.md index c9608b8543235f62099288126d6488427e6135e2..db907bd005b61e3590b8c97de7943604c81d92cb 100644 --- a/zh-cn/application-dev/napi/native-image-guidelines.md +++ b/zh-cn/application-dev/napi/native-image-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -NativeImage是`OpenHarmony`提供**Surface关联OpenGL外部纹理**的模块,表示图形队列的消费者端。开发者可以通过`NativeImage`接口接收和使用`Buffer`,并将`Buffer`关联输出到OpenGL外部纹理。 +NativeImage是提供**Surface关联OpenGL外部纹理**的模块,表示图形队列的消费者端。开发者可以通过`NativeImage`接口接收和使用`Buffer`,并将`Buffer`关联输出到OpenGL外部纹理。 针对NativeImage,常见的开发场景如下: * 通过`NativeImage`提供的Native API接口创建`NativeImage`实例作为消费者端,获取与该实例对应的`NativeWindow`作为生产者端。`NativeWindow`相关接口可用于填充`Buffer`内容并提交,`NativeImage`将`Buffer`内容更新到OpenGL外部纹理上。本模块需要配合NativeWindow、NativeBuffer、EGL、GLES3模块一起使用。 @@ -24,7 +24,7 @@ NativeImage是`OpenHarmony`提供**Surface关联OpenGL外部纹理**的模块, ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeImage`提供的Native API接口,创建`OH_NativeImage`实例作为消费者端,将数据内容更新到OpenGL外部纹理上。 +以下步骤描述了如何使用`NativeImage`提供的Native API接口,创建`OH_NativeImage`实例作为消费者端,将数据内容更新到OpenGL外部纹理上。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/native-vsync-guidelines.md b/zh-cn/application-dev/napi/native-vsync-guidelines.md index 9e0c68bd95332241dba2dec9d94552b6f216dbcb..4d48e15d2cfe4507b6c5a200825771343cea05a9 100644 --- a/zh-cn/application-dev/napi/native-vsync-guidelines.md +++ b/zh-cn/application-dev/napi/native-vsync-guidelines.md @@ -17,7 +17,7 @@ NativeVsync模块用来获取系统VSync信号,提供了OH_NativeVSync实例 ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeVsync`提供的Native API接口,创建和销毁`OH_NativeVsync`实例,以及如何设置VSync回调函数。 +以下步骤描述了如何使用`NativeVsync`提供的Native API接口,创建和销毁`OH_NativeVsync`实例,以及如何设置VSync回调函数。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/native-window-guidelines.md b/zh-cn/application-dev/napi/native-window-guidelines.md index acdfedde2aea97e7e7c95372ff2e295696ec8323..8b86276da19eae3aa3fbc3ec0020cee611d1b0a4 100644 --- a/zh-cn/application-dev/napi/native-window-guidelines.md +++ b/zh-cn/application-dev/napi/native-window-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生产者端。开发者可以通过`NativeWindow`接口进行申请和提交`Buffer`,配置`Buffer`属性信息。 +NativeWindow是**本地平台化窗口**,表示图形队列的生产者端。开发者可以通过`NativeWindow`接口进行申请和提交`Buffer`,配置`Buffer`属性信息。 针对NativeWindow,常见的开发场景如下: * 通过`NativeWindow`提供的Native API接口申请图形`Buffer`,并将生产图形内容写入图形`Buffer`,最终提交`Buffer`到图形队列 @@ -20,7 +20,7 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生 ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeWindow`提供的Native API接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列。 +以下步骤描述了如何使用`NativeWindow`提供的Native API接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md index bdde437188c2cc9a9da8ddbdcb2b2eec1056c61b..d05f540dd98779e89b1fa587a6f3b71288e536f5 100644 --- a/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md +++ b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md @@ -19,7 +19,7 @@ Neural Network Runtime部件的环境要求如下: - 开发环境:Ubuntu 18.04及以上。 - 接入设备:OpenHarmony定义的标准设备,并且系统中内置的硬件加速器驱动,已通过HDI接口对接Neural Network Runtime。 -由于Neural Network Runtime通过OpenHarmony Native API对外开放,需要通过OpenHarmony的Native开发套件编译Neural Network Runtime应用。 +由于Neural Network Runtime通过Native API对外开放,需要通过Native开发套件编译Neural Network Runtime应用。 ### 环境搭建 diff --git a/zh-cn/application-dev/napi/usb-ddk-guidelines.md b/zh-cn/application-dev/napi/usb-ddk-guidelines.md index 9bef6a793dfc93f9dc0cd5763e61157d17fbc7e7..d3d8a45ac970bb9fc35c3cc5a948731765bca31e 100644 --- a/zh-cn/application-dev/napi/usb-ddk-guidelines.md +++ b/zh-cn/application-dev/napi/usb-ddk-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -USB DDK(USB Driver Develop Kit)是OpenHarmony为开发者提供的USB驱动程序开发套件,支持开发者基于用户态,在应用层开发USB设备驱动。提供了一系列主机侧访问设备的接口,包括主机侧打开和关闭接口、管道同步异步读写通信、控制传输、中断传输等。 +USB DDK(USB Driver Develop Kit)是为开发者提供的USB驱动程序开发套件,支持开发者基于用户态,在应用层开发USB设备驱动。提供了一系列主机侧访问设备的接口,包括主机侧打开和关闭接口、管道同步异步读写通信、控制传输、中断传输等。 ## 接口说明 @@ -23,7 +23,7 @@ USB DDK(USB Driver Develop Kit)是OpenHarmony为开发者提供的USB驱动 ## USB DDK开发步骤 -以下步骤描述了在**OpenHarmony**如何使用 **USB DDK**开发USB驱动: +以下步骤描述了如何使用 **USB DDK**开发USB驱动: 1. **获取设备描述符**。使用 **usb_ddk_api.h** 的 **OH_Usb_Init** 接口初始化DDK,并使用 **OH_Usb_GetDeviceDescriptor**获取到设备描述符。 diff --git a/zh-cn/application-dev/napi/vulkan-guidelines.md b/zh-cn/application-dev/napi/vulkan-guidelines.md index bc14fbe7a73ef93eb52de1795bdc6f0d0837b511..95da4d0a4660a3df91725794c4493b4041d89679 100644 --- a/zh-cn/application-dev/napi/vulkan-guidelines.md +++ b/zh-cn/application-dev/napi/vulkan-guidelines.md @@ -16,9 +16,9 @@ Vulkan是一套用来做2D和3D渲染的图形应用程序接口,其中创建V ## 开发步骤 -以下步骤说明了如何在OpenHarmony平台创建一个VkSurfaceKHR对象。 +以下步骤说明了如何创建一个VkSurfaceKHR对象。 -首先,使用OpenHarmony平台扩展的接口,需要定义一个宏`VK_USE_PLATFORM_OHOS`,我们在CMakeLists.txt定义这个宏。 +首先,使用平台扩展的接口,需要定义一个宏`VK_USE_PLATFORM_OHOS`,我们在CMakeLists.txt定义这个宏。 ```txt ADD_DEFINITIONS(-DVK_USE_PLATFORM_OHOS=1) ``` @@ -56,7 +56,7 @@ libvulkan.so std::vector instanceExtensions = { VK_KHR_SURFACE_EXTENSION_NAME, - VK_OHOS_SURFACE_EXTENSION_NAME // OpenHarmony平台的Surface扩展 + VK_OHOS_SURFACE_EXTENSION_NAME // Surface扩展 }; instanceCreateInfo.enabledExtensionCount = static_cast(instanceExtensions.size()); instanceCreateInfo.ppEnabledExtensionNames = instanceExtensions.data(); diff --git a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md index dbb87f4612f671489bea67fbee6013e22f6fbb29..daad5a996516e5d43594c3dc08211cb09e937726 100644 --- a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md +++ b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md @@ -69,12 +69,12 @@ OpenHarmony的应用冷启动过程大致可分成以下四个阶段:应用进 aboutToAppear函数会在创建自定义组件实例后,页面绘制之前执行,以下代码在aboutToAppear中对耗时长的计算任务进行了异步处理,避免在该接口执行该耗时操作,不阻塞页面绘制。 -```javascript +```typescript @Entry @Component struct Index { - @State private text: string = undefined; - private count: number = undefined; + @State private text: string = ""; + private count: number = 0; aboutToAppear() { this.computeTaskAsync(); // 异步任务 @@ -100,11 +100,9 @@ struct Index { // 运算任务异步处理 private computeTaskAsync() { - new Promise((resolved, rejected) => { - setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 - this.computeTask(); - }, 1000) - }) + setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 + this.computeTask(); + }, 1000) } } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md index acd7a634b8855d8de10a7fa0162d27d81f164b32..b21b23596146c7885b6f6a3d7f98b5c7ecc01b70 100644 --- a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md +++ b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md @@ -13,7 +13,7 @@ OpenHarmony提供的Image组件默认生效异步加载特性,当应用在页面上展示一批本地图片的时候,会先显示空白占位块,当图片在其他线程加载完毕后,再替换占位块。这样图片加载就可以不阻塞页面的显示,给用户带来良好的交互体验。因此,只在加载图片耗时比较短的情况下建议下述代码。 -```javascript +```typescript @Entry @Component struct ImageExample1 { @@ -37,10 +37,10 @@ struct ImageExample1 { 建议:在加载图片的耗时比较短的时候,通过异步加载的效果会大打折扣,建议配置Image的syncLoad属性。 -```javascript +```typescript @Entry @Component -struct ImageExample1 { +struct ImageExample2 { build() { Column() { Row() { @@ -63,7 +63,7 @@ struct ImageExample1 { OpenHarmony提供了[TaskPool线程池](../../reference/apis/js-apis-taskpool.md),相比worker线程,TaskPool提供了任务优先级设置、线程池自动管理机制,示例如下: -```javascript +```typescript import taskpool from '@ohos.taskpool'; @Concurrent @@ -78,7 +78,7 @@ function computeTask(arr: string[]): string[] { @Entry @Component -struct AspectRatioExample { +struct AspectRatioExample3 { @State children: string[] = ['1', '2', '3', '4', '5', '6']; aboutToAppear() { @@ -88,8 +88,7 @@ struct AspectRatioExample { async computeTaskInTaskPool() { const param = this.children.slice(); let task = new taskpool.Task(computeTask, param); - // @ts-ignore - this.children = await taskpool.execute(task); + await taskpool.execute(task); } build() { @@ -102,12 +101,12 @@ struct AspectRatioExample { 以下代码展示了将一个长时间执行的非UI任务通过Promise声明成异步任务,主线程可以先进行用户反馈-绘制初始页面。等主线程空闲时,再执行异步任务。等到异步任务运行完毕后,重绘相关组件刷新页面。 -```javascript +```typescript @Entry @Component -struct AspectRatioExample { +struct AspectRatioExample4 { @State private children: string[] = ['1', '2', '3', '4', '5', '6']; - private count: number = undefined; + private count: number = 0; aboutToAppear() { this.computeTaskAsync(); // 调用异步运算函数 @@ -123,11 +122,9 @@ struct AspectRatioExample { } computeTaskAsync() { - new Promise((resolved, rejected) => { - setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 - this.computeTask(); - }, 1000) - }) + setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 + this.computeTask(); + }, 1000) } build() { @@ -146,10 +143,10 @@ struct AspectRatioExample { 以下代码的Text('New Page')组件被状态变量isVisible控制,isVisible为true时创建,false时销毁。当isVisible发生变化时,Stack容器内的所有组件都会刷新: -```javascript +```typescript @Entry @Component -struct StackExample { +struct StackExample5 { @State isVisible : boolean = false; build() { @@ -175,10 +172,10 @@ struct StackExample { 建议:对于这种受状态变量控制的组件,在if外套一层容器,减少刷新范围。 -```javascript +```typescript @Entry @Component -struct StackExample { +struct StackExample6 { @State isVisible : boolean = false; build() { @@ -208,11 +205,11 @@ struct StackExample { 反例:this.arr中的每一项元素都被初始化和加载,数组中的元素有10000个,主线程执行耗时长。 -```javascript +```typescript @Entry @Component -struct MyComponent { - @State arr: number[] = Array.from(Array(10000), (v,k) =>k); +struct MyComponent7 { + @State arr: number[] = Array.from(Array(10000), (v,k) =>k); build() { List() { ForEach(this.arr, (item: number) => { @@ -227,7 +224,7 @@ struct MyComponent { 建议:这种情况下用LazyForEach替换ForEach,LazyForEach一般只加载可见的元素,避免一次性初始化和加载所有元素。 -```javascript +```typescript class BasicDataSource implements IDataSource { private listeners: DataChangeListener[] = [] @@ -235,8 +232,8 @@ class BasicDataSource implements IDataSource { return 0 } - public getData(index: number): any { - return undefined + public getData(index: number): string { + return '' } registerDataChangeListener(listener: DataChangeListener): void { @@ -286,13 +283,13 @@ class BasicDataSource implements IDataSource { } class MyDataSource extends BasicDataSource { - private dataArray: string[] = Array.from(Array(10000), (v, k) => k.toString()); + private dataArray: string[] = Array.from(Array(10000), (v, k) => k.toString()); public totalCount(): number { return this.dataArray.length } - public getData(index: number): any { + public getData(index: number): string { return this.dataArray[index] } @@ -318,7 +315,7 @@ struct MyComponent { ListItem() { Text(item).fontSize(20).margin({ left: 10 }) } - }, item => item) + }, (item:string) => item) } } } diff --git a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md index caaf5d22815504e5293e0a1a5990ed56a363a9c0..8e677d2e542d663f00b7ffaacc0a5fbab8b140b5 100644 --- a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md +++ b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md @@ -6,7 +6,7 @@ 反例:应用使用了自定义动画,动画曲线计算过程很容易引起UI线程高负载,易导致丢帧。 -```javascript +```typescript @Entry @Component struct AttrAnimationExample { @@ -17,8 +17,8 @@ struct AttrAnimationExample { computeSize() { let duration = 2000 let period = 16 - let widthSizeEnd = undefined - let heightSizeEnd = undefined + let widthSizeEnd = 0 + let heightSizeEnd = 0 if (this.flag) { widthSizeEnd = 100 heightSizeEnd = 50 @@ -56,7 +56,7 @@ struct AttrAnimationExample { 建议:通过系统提供的属性动效API实现上述动效功能。 -```javascript +```typescript @Entry @Component struct AttrAnimationExample { @@ -67,7 +67,7 @@ struct AttrAnimationExample { build() { Column() { Button('click me') - .onClick((event: ClickEvent) => { + .onClick((event?: ClickEvent | undefined) => { if (this.flag) { this.widthSize = 100 this.heightSize = 50 @@ -96,7 +96,7 @@ struct AttrAnimationExample { 建议:通过系统提供的显式动效API实现上述动效功能。 -```javascript +```typescript @Entry @Component struct AnimateToExample { @@ -107,7 +107,7 @@ struct AnimateToExample { build() { Column() { Button('click me') - .onClick((event: ClickEvent) => { + .onClick((event?: ClickEvent | undefined) => { if (this.flag) { animateTo({ duration: 2000, // 动画时长 diff --git a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md index ab4cf3697a3fdf5a9033019112b9d732ec05a401..c9337880dfaa220cfbac775d5586517ed6458c55 100644 --- a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md +++ b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md @@ -6,16 +6,16 @@ 反例:使用了Grid来实现一个网格,但是在外层套了3层stack容器,导致组件刷新和渲染耗时长。 -```javascript +```typescript @Entry @Component -struct AspectRatioExample { - @State children: Number[] = Array.from(Array(900), (v, k) => k); +struct AspectRatioExample12 { + @State children: Number[] = Array.from(Array(900), (v, k) => k); build() { Scroll() { Grid() { - ForEach(this.children, (item) => { + ForEach(this.children, (item:Number[]) => { GridItem() { Stack() { Stack() { @@ -25,7 +25,7 @@ struct AspectRatioExample { } } } - }, item => item) + }, (item:string) => item) } .columnsTemplate('1fr 1fr 1fr 1fr') .columnsGap(0) @@ -38,21 +38,20 @@ struct AspectRatioExample { 建议:通过减少冗余的Stack容器嵌套,每个GridItem的组件数比上面少了3个,缩短了组件刷新与渲染耗时。 -```javascript -// xxx.ets +```typescript @Entry @Component -struct AspectRatioExample { +struct AspectRatioExample11 { @State children: Number[] = Array.from(Array(900), (v, k) => k); build() { Scroll() { Grid() { - ForEach(this.children, (item) => { + ForEach(this.children, (item:Number[]) => { GridItem() { Text(item.toString()) } - }, item => item) + }, (item:string) => item) } .columnsTemplate('1fr 1fr 1fr 1fr') .columnsGap(0) diff --git a/zh-cn/application-dev/quick-start/arkts-builder.md b/zh-cn/application-dev/quick-start/arkts-builder.md index 276ee2f8fd48bd2a8bfac77906ceb71204174cd7..dc0df2d9b2c1172534ddccb4acda382d858b9ada 100644 --- a/zh-cn/application-dev/quick-start/arkts-builder.md +++ b/zh-cn/application-dev/quick-start/arkts-builder.md @@ -21,14 +21,14 @@ ```ts -@Builder MyBuilderFunction({ ... }) +@Builder MyBuilderFunction() { ... } ``` 使用方法: ```ts -this.MyBuilderFunction({ ... }) +this.MyBuilderFunction() { ... } ``` - 允许在自定义组件内定义一个或多个自定义构建函数,该函数被认为是该组件的私有、特殊类型的成员函数。 @@ -44,7 +44,7 @@ this.MyBuilderFunction({ ... }) ```ts -@Builder function MyGlobalBuilderFunction({ ... }) +@Builder function MyGlobalBuilderFunction() { ... } ``` 使用方法: @@ -82,7 +82,7 @@ class ABuilderParam { paramB1: string = '' } -ABuilder($$ : ABuilderParam); +@Builder function ABuilder($$ : ABuilderParam) {...} ``` diff --git a/zh-cn/application-dev/quick-start/arkts-builderparam.md b/zh-cn/application-dev/quick-start/arkts-builderparam.md index 8151b6e8eb4ed82a4103206871025f18dd6e6488..9e1ca6bc87cce2b06c5cddb8c7f78d9cae79997e 100644 --- a/zh-cn/application-dev/quick-start/arkts-builderparam.md +++ b/zh-cn/application-dev/quick-start/arkts-builderparam.md @@ -34,34 +34,34 @@ - 用父组件自定义构建函数初始化子组件\@BuildParam装饰的方法。 ```ts -@Component -struct Child { - @Builder componentBuilder() { - Text(`Parent builder `) - } + @Component + struct Child { + @Builder componentBuilder() { + Text(`Parent builder `) + } - @BuilderParam aBuilder0: () => void = this.componentBuilder; + @BuilderParam aBuilder0: () => void = this.componentBuilder; - build() { - Column() { - this.aBuilder0() + build() { + Column() { + this.aBuilder0() + } } } -} -@Entry -@Component -struct Parent { - @Builder componentBuilder() { - Text(`Parent builder `) - } + @Entry + @Component + struct Parent { + @Builder componentBuilder() { + Text(`Parent builder `) + } - build() { - Column() { - Child({ aBuilder0: this.componentBuilder }) + build() { + Column() { + Child({ aBuilder0: this.componentBuilder }) + } } } -} ``` @@ -74,40 +74,40 @@ struct Parent { > 开发者谨慎使用bind改变函数调用的上下文,可能会使this指向混乱。 ```ts -@Component -struct Child { - @Builder componentBuilder() { - Text(`Child builder `) - } + @Component + struct Child { + @Builder componentBuilder() { + Text(`Child builder `) + } - label: string = `Child` - @BuilderParam aBuilder0: () => void = this.componentBuilder; - @BuilderParam aBuilder1: () => void = this.componentBuilder; + label: string = `Child` + @BuilderParam aBuilder0: () => void = this.componentBuilder; + @BuilderParam aBuilder1: () => void = this.componentBuilder; - build() { - Column() { - this.aBuilder0() - this.aBuilder1() + build() { + Column() { + this.aBuilder0() + this.aBuilder1() + } } } -} -@Entry -@Component -struct Parent { - label: string = `Parent` + @Entry + @Component + struct Parent { + label: string = `Parent` - @Builder componentBuilder() { - Text(`${this.label}`) - } + @Builder componentBuilder() { + Text(`${this.label}`) + } - build() { - Column() { - this.componentBuilder() - Child({ aBuilder0: this.componentBuilder, aBuilder1: this.componentBuilder }) + build() { + Column() { + this.componentBuilder() + Child({ aBuilder0: this.componentBuilder, aBuilder1: this.componentBuilder }) + } } } -} ``` diff --git a/zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md b/zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md index e31bb7049356983368173d97bdb98684edf6b463..41e68029b56746a590f6601fcd6dff065d976453 100644 --- a/zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md +++ b/zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md @@ -116,13 +116,13 @@ Column() { }) ``` -- 使用匿名函数表达式配置组件的事件方法,要求使用bind,以确保函数体中的this指向当前组件。 +- 使用匿名函数表达式配置组件的事件方法,要求使用“() => {...}”,以确保函数与组件绑定,同时符合ArtTS语法规范。 ```ts Button('add counter') - .onClick(function(){ + .onClick(() => { this.counter += 2; - }.bind(this)) + }) ``` - 使用组件的成员函数配置组件的事件方法。 @@ -133,7 +133,7 @@ Column() { } ... Button('add counter') - .onClick(this.myClickHandler.bind(this)) + .onClick(this.myClickHandler) ``` diff --git a/zh-cn/application-dev/quick-start/arkts-localstorage.md b/zh-cn/application-dev/quick-start/arkts-localstorage.md index 63b1c53b398e851c7d5923f006a8743fbeef72a7..526a72137d547f20c8f61863dc2bfeda1256fa12 100644 --- a/zh-cn/application-dev/quick-start/arkts-localstorage.md +++ b/zh-cn/application-dev/quick-start/arkts-localstorage.md @@ -191,37 +191,37 @@ link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49 - \@LocalStorageLink绑定LocalStorage对给定的属性,建立双向数据同步。 ```ts -// 创建新实例并使用给定对象初始化 -let storage = new LocalStorage(); -storage['PropA'] = 47; - -@Component -struct Child { - // @LocalStorageLink变量装饰器与LocalStorage中的'PropA'属性建立双向绑定 - @LocalStorageLink('PropA') storLink2: number = 1; - - build() { - Button(`Child from LocalStorage ${this.storLink2}`) - // 更改将同步至LocalStorage中的'PropA'以及Parent.storLink1 - .onClick(() => this.storLink2 += 1) + // 创建新实例并使用给定对象初始化 + let storage = new LocalStorage(); + storage['PropA'] = 47; + + @Component + struct Child { + // @LocalStorageLink变量装饰器与LocalStorage中的'PropA'属性建立双向绑定 + @LocalStorageLink('PropA') storLink2: number = 1; + + build() { + Button(`Child from LocalStorage ${this.storLink2}`) + // 更改将同步至LocalStorage中的'PropA'以及Parent.storLink1 + .onClick(() => this.storLink2 += 1) + } } -} -// 使LocalStorage可从@Component组件访问 -@Entry(storage) -@Component -struct CompA { - // @LocalStorageLink变量装饰器与LocalStorage中的'PropA'属性建立双向绑定 - @LocalStorageLink('PropA') storLink1: number = 1; - - build() { - Column({ space: 15 }) { - Button(`Parent from LocalStorage ${this.storLink1}`) // initial value from LocalStorage will be 47, because 'PropA' initialized already - .onClick(() => this.storLink1 += 1) - // @Component子组件自动获得对CompA LocalStorage实例的访问权限。 - Child() + // 使LocalStorage可从@Component组件访问 + @Entry(storage) + @Component + struct CompA { + // @LocalStorageLink变量装饰器与LocalStorage中的'PropA'属性建立双向绑定 + @LocalStorageLink('PropA') storLink1: number = 1; + + build() { + Column({ space: 15 }) { + Button(`Parent from LocalStorage ${this.storLink1}`) // initial value from LocalStorage will be 47, because 'PropA' initialized already + .onClick(() => this.storLink1 += 1) + // @Component子组件自动获得对CompA LocalStorage实例的访问权限。 + Child() + } } } -} ``` @@ -234,39 +234,39 @@ struct CompA { - Child组件中,Text绑定的storProp2 依旧显示47。 ```ts -// 创建新实例并使用给定对象初始化 -let storage = new LocalStorage(); -storage['PropA'] = 47; - -// 使LocalStorage可从@Component组件访问 -@Entry(storage) -@Component -struct CompA { - // @LocalStorageProp变量装饰器与LocalStorage中的'PropA'属性建立单向绑定 - @LocalStorageProp('PropA') storProp1: number = 1; - - build() { - Column({ space: 15 }) { - // 点击后从47开始加1,只改变当前组件显示的storProp1,不会同步到LocalStorage中 - Button(`Parent from LocalStorage ${this.storProp1}`) - .onClick(() => this.storProp1 += 1) - Child() + // 创建新实例并使用给定对象初始化 + let storage = new LocalStorage(); + storage['PropA'] = 47; + + // 使LocalStorage可从@Component组件访问 + @Entry(storage) + @Component + struct CompA { + // @LocalStorageProp变量装饰器与LocalStorage中的'PropA'属性建立单向绑定 + @LocalStorageProp('PropA') storProp1: number = 1; + + build() { + Column({ space: 15 }) { + // 点击后从47开始加1,只改变当前组件显示的storProp1,不会同步到LocalStorage中 + Button(`Parent from LocalStorage ${this.storProp1}`) + .onClick(() => this.storProp1 += 1) + Child() + } } } -} -@Component -struct Child { - // @LocalStorageProp变量装饰器与LocalStorage中的'PropA'属性建立单向绑定 - @LocalStorageProp('PropA') storProp2: number = 2; + @Component + struct Child { + // @LocalStorageProp变量装饰器与LocalStorage中的'PropA'属性建立单向绑定 + @LocalStorageProp('PropA') storProp2: number = 2; - build() { - Column({ space: 15 }) { - // 当CompA改变时,当前storProp2不会改变,显示47 - Text(`Parent from LocalStorage ${this.storProp2}`) + build() { + Column({ space: 15 }) { + // 当CompA改变时,当前storProp2不会改变,显示47 + Text(`Parent from LocalStorage ${this.storProp2}`) + } } } -} ``` diff --git a/zh-cn/application-dev/quick-start/arkts-mvvm.md b/zh-cn/application-dev/quick-start/arkts-mvvm.md index 8f0a9b1fb98430d34f544c8cc7f0b98b71333ca7..ca4ef0d0aeba15e50322092cbdf580957a289191 100644 --- a/zh-cn/application-dev/quick-start/arkts-mvvm.md +++ b/zh-cn/application-dev/quick-start/arkts-mvvm.md @@ -125,7 +125,7 @@ ViewModel通常包含多个顶层数据源。\@State和\@Provide装饰的变量 ```ts @Component struct LinkLinkChild { - @Link @Watch("testNumChange") testNumGrand: number; + @Link @Watch("testNumChange") testNumGrand: number = 0; testNumChange(propName: string): void { console.log(`LinkLinkChild: testNumGrand value ${this.testNumGrand}`); @@ -139,7 +139,7 @@ ViewModel通常包含多个顶层数据源。\@State和\@Provide装饰的变量 @Component struct PropLinkChild { - @Prop @Watch("testNumChange") testNumGrand: number; + @Prop @Watch("testNumChange") testNumGrand: number = 0; testNumChange(propName: string): void { console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`); @@ -175,7 +175,7 @@ ViewModel通常包含多个顶层数据源。\@State和\@Provide装饰的变量 ```ts @Component struct LinkLinkChild { - @Link @Watch("testNumChange") testNumGrand: number; + @Link @Watch("testNumChange") testNumGrand: number = 0; testNumChange(propName: string): void { console.log(`LinkLinkChild: testNumGrand value ${this.testNumGrand}`); @@ -189,7 +189,7 @@ ViewModel通常包含多个顶层数据源。\@State和\@Provide装饰的变量 @Component struct PropLinkChild { - @Prop @Watch("testNumChange") testNumGrand: number; + @Prop @Watch("testNumChange") testNumGrand: number = 0; testNumChange(propName: string): void { console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`); @@ -277,7 +277,7 @@ ViewModel通常包含多个顶层数据源。\@State和\@Provide装饰的变量 ```ts @Component struct LinkLinkChild { - @Consume @Watch("testNumChange") testNum: number; + @Consume @Watch("testNumChange") testNum: number = 0; testNumChange(propName: string): void { console.log(`LinkLinkChild: testNum value ${this.testNum}`); @@ -290,7 +290,7 @@ struct LinkLinkChild { @Component struct PropLinkChild { - @Prop @Watch("testNumChange") testNumGrand: number; + @Prop @Watch("testNumChange") testNumGrand: number = 0; testNumChange(propName: string): void { console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`); @@ -609,7 +609,7 @@ struct Parent { ```ts @Observed class ObservedArray extends Array { - constructor(args: any[]) { + constructor(args: T[]) { super(...args); } /* otherwise empty */ @@ -621,7 +621,7 @@ struct Parent { ```ts class Outer { - innerArrayProp : ObservedArray; + innerArrayProp : ObservedArray = []; ... } ``` @@ -686,10 +686,10 @@ struct ViewB { build() { Column() { ForEach(this.arrA, - (item) => { + (item: ClassA) => { ViewA({ label: `#${item.id}`, a: item }) }, - (item) => 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() { @@ -875,9 +875,9 @@ export class Person { ```ts @Observed export class ObservedArray extends Array { - constructor(args?: any[]) { + constructor(args: T[]) { console.log(`ObservedArray: ${JSON.stringify(args)} `) - if (Array.isArray(args)) { + if (args instanceof Array) { super(...args); } else { super(args) @@ -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; @@ -916,13 +916,12 @@ export class ObservedArray extends Array { Divider().height(8) - ForEach(this.contacts, - contact => { - PersonView({person: contact, phones: contact.phones, selectedPerson: this.$selectedPerson}) - }, - contact => contact.id_ - ) - + ForEach(this.contacts, (contact: Person) => { + PersonView({ person: contact, phones: contact.phones as ObservedArray, selectedPerson: this.$selectedPerson }) + }, + (contact: Person): string => { return contact.id_; } + ) + Divider().height(8) Text("Edit:") @@ -971,7 +970,7 @@ export class ObservedArray extends Array { build() { Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { Text(this.person.name) - if (this.phones.length) { + if (this.phones.length > 0) { Text(this.phones[0]) } } @@ -1005,12 +1004,12 @@ export class ObservedArray extends Array { @Link selectedPerson: Person; /*在本地副本上编辑,直到点击保存*/ - @Prop name: string; - @Prop address : Address; - @Prop phones : ObservedArray; + @Prop name: string = ""; + @Prop address : Address = new Address("", 0, ""); + @Prop phones : ObservedArray = []; selectedPersonIndex() : number { - return this.addrBook.contacts.findIndex((person) => person.id_ == this.selectedPerson.id_); + return this.addrBook.contacts.findIndex((person: Person) => person.id_ == this.selectedPerson.id_); } build() { @@ -1031,24 +1030,24 @@ export class ObservedArray extends Array { TextInput({text: this.address.zip.toString()}) .onChange((value) => { - const result = parseInt(value); - this.address.zip= isNaN(result) ? 0 : result; + const result = Number.parseInt(value); + this.address.zip= Number.isNaN(result) ? 0 : result; }) - if(this.phones.length>0) { - ForEach(this.phones, - (phone, index) => { - TextInput({text: phone}) - .width(150) - .onChange((value) => { - console.log(`${index}. ${value} value has changed`) - this.phones[index] = value; - }) - }, - (phone, index) => `${index}-${phone}` - ) + if (this.phones.length > 0) { + ForEach(this.phones, + (phone: ResourceStr, index?:number) => { + TextInput({ text: phone }) + .width(150) + .onChange((value) => { + console.log(`${index}. ${value} value has changed`) + this.phones[index!] = value; + }) + }, + (phone: ResourceStr, index?:number) => `${index}-${phone}` + ) } - + Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { Text("Save Changes") .onClick(() => { @@ -1103,25 +1102,25 @@ export class ObservedArray extends Array { // ViewModel classes let nextId = 0; - + @Observed export class ObservedArray extends Array { - constructor(args?: any[]) { + constructor(args: T[]) { console.log(`ObservedArray: ${JSON.stringify(args)} `) - if (Array.isArray(args)) { + if (args instanceof Array) { super(...args); } else { super(args) } } } - + @Observed export class Address { street: string; zip: number; city: string; - + constructor(street: string, zip: number, city: string) { @@ -1130,14 +1129,14 @@ export class ObservedArray extends Array { this.city = city; } } - + @Observed export class Person { id_: string; name: string; address: Address; phones: ObservedArray; - + constructor(name: string, street: string, zip: number, @@ -1154,13 +1153,13 @@ export class ObservedArray extends Array { export class AddressBook { me: Person; contacts: ObservedArray; - + constructor(me: Person, contacts: Person[]) { this.me = me; this.contacts = new ObservedArray(contacts); } } - + //渲染出Person对象的名称和Observed数组中的第一个号码 //为了更新电话号码,这里需要@ObjectLink person和@ObjectLink phones, //不能使用this.person.phones,内部数组的更改不会被观察到。 @@ -1170,7 +1169,7 @@ export class ObservedArray extends Array { @ObjectLink person: Person; @ObjectLink phones: ObservedArray; @Link selectedPerson: Person; - + build() { Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { Text(this.person.name) @@ -1185,26 +1184,26 @@ export class ObservedArray extends Array { }) } } - + // 渲染Person的详细信息 // @Prop装饰的变量从父组件AddressBookView深拷贝数据,将变化保留在本地, TextInput的变化只会在本地副本上进行修改。 // 点击 "Save Changes" 会将所有数据的复制通过@Prop到@Link, 同步到其他组件 @Component struct PersonEditView { @Consume addrBook: AddressBook; - + /* 指向父组件selectedPerson的引用 */ @Link selectedPerson: Person; - + /*在本地副本上编辑,直到点击保存*/ - @Prop name: string; - @Prop address: Address; - @Prop phones: ObservedArray; - + @Prop name: string = ""; + @Prop address: Address = new Address("", 0, ""); + @Prop phones: ObservedArray = []; + selectedPersonIndex(): number { - return this.addrBook.contacts.findIndex((person) => person.id_ == this.selectedPerson.id_); + return this.addrBook.contacts.findIndex((person: Person) => person.id_ == this.selectedPerson.id_); } - + build() { Column() { TextInput({ text: this.name }) @@ -1215,32 +1214,32 @@ export class ObservedArray extends Array { .onChange((value) => { this.address.street = value; }) - + TextInput({ text: this.address.city }) .onChange((value) => { this.address.city = value; }) - + TextInput({ text: this.address.zip.toString() }) .onChange((value) => { - const result = parseInt(value); - this.address.zip = isNaN(result) ? 0 : result; + const result = Number.parseInt(value); + this.address.zip = Number.isNaN(result) ? 0 : result; }) - + if (this.phones.length > 0) { ForEach(this.phones, - (phone, index) => { + (phone: ResourceStr, index?:number) => { TextInput({ text: phone }) .width(150) .onChange((value) => { console.log(`${index}. ${value} value has changed`) - this.phones[index] = value; + this.phones[index!] = value; }) }, - (phone, index) => `${index}-${phone}` + (phone: ResourceStr, index?:number) => `${index}-${phone}` ) } - + Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { Text("Save Changes") .onClick(() => { @@ -1259,49 +1258,48 @@ export class ObservedArray extends Array { .onClick(() => { let index = this.selectedPersonIndex(); console.log(`delete contact at index ${index}`); - + // 删除当前联系人 this.addrBook.contacts.splice(index, 1); - + // 删除当前selectedPerson,选中态前移一位 index = (index < this.addrBook.contacts.length) ? index : index - 1; - + // 如果contract被删除完,则设置me为选中态 this.selectedPerson = (index >= 0) ? this.addrBook.contacts[index] : this.addrBook.me; }) } } - + } } } - + @Component struct AddressBookView { @ObjectLink me: Person; @ObjectLink contacts: ObservedArray; - @State selectedPerson: Person = undefined; - + @State selectedPerson: Person = new Person("", "", 0, "", []); + aboutToAppear() { this.selectedPerson = this.me; } - + build() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start }) { Text("Me:") PersonView({ person: this.me, phones: this.me.phones, selectedPerson: this.$selectedPerson }) - + Divider().height(8) - - ForEach(this.contacts, - contact => { - PersonView({ person: contact, phones: contact.phones, selectedPerson: this.$selectedPerson }) - }, - contact => contact.id_ + + ForEach(this.contacts, (contact: Person) => { + PersonView({ person: contact, phones: contact.phones as ObservedArray, selectedPerson: this.$selectedPerson }) + }, + (contact: Person): string => { return contact.id_; } ) - + Divider().height(8) - + Text("Edit:") PersonEditView({ selectedPerson: this.$selectedPerson, @@ -1313,7 +1311,7 @@ export class ObservedArray extends Array { .borderStyle(BorderStyle.Solid).borderWidth(5).borderColor(0xAFEEEE).borderRadius(5) } } - + @Entry @Component struct PageEntry { @@ -1324,7 +1322,7 @@ export class ObservedArray extends Array { new Person("Sam", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), new Person("Vivi", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), ]); - + build() { Column() { AddressBookView({ me: this.addrBook.me, contacts: this.addrBook.contacts, selectedPerson: this.addrBook.me }) diff --git a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md index 538c27e9e0787af8ced563bef4f0076b6e856b1b..e4c7838e12ec0ce594ea78ebcbaaf1a9732f4eb6 100644 --- a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -346,7 +346,7 @@ struct ViewB { (item: ClassA) => { ViewA({ label: `#${item.id}`, a: item }) }, - (item: ClassA) => item.id.toString() + (item: ClassA): string => item.id.toString() ) // 使用@State装饰的数组的数组项初始化@ObjectLink,其中数组项是被@Observed装饰的ClassA的实例 ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] }) diff --git a/zh-cn/application-dev/quick-start/arkts-prop.md b/zh-cn/application-dev/quick-start/arkts-prop.md index 9250154d01eb42c8c6c56c47b30dc586621f0b00..12b19eac88c0acf63342cc0aeb93cab0f678044c 100644 --- a/zh-cn/application-dev/quick-start/arkts-prop.md +++ b/zh-cn/application-dev/quick-start/arkts-prop.md @@ -264,7 +264,7 @@ struct ParentComponent { ```ts @Component struct Child { - @Prop value: number; + @Prop value: number = 0; build() { Text(`${this.value}`) @@ -288,10 +288,10 @@ struct Index { Divider().height(5) ForEach(this.arr, - item => { + (item: void) => { Child({value: item}) }, - item => item.toString() + (item: string) => item.toString() ) Text('replace entire arr') .fontSize(50) diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control-best-practices.md b/zh-cn/application-dev/quick-start/arkts-rendering-control-best-practices.md index 5afba0367e9bf5c41c6d9c168faa95083e9d9faf..1b63c2c9a6872f991794d39f3d88dae16e7d61e6 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control-best-practices.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control-best-practices.md @@ -22,10 +22,10 @@ struct Index { build() { Column() { ForEach(this.arr, - (item) => { + (item: void) => { Text(`Item ${item}`) }, - item => item.toString()) + (item: string) => item.toString()) Text('Add arr element') .fontSize(20) .onClick(()=>{ @@ -61,7 +61,7 @@ ForEach数据源更新时,数组项ID与原数组项ID重复不会重新创建 ```ts @Component struct Child { - @Prop value: number; + @Prop value: number = 0; build() { Text(`${this.value}`) .fontSize(50) @@ -83,10 +83,10 @@ struct Index { Child({ value: this.arr[2] }) Divider().height(5) ForEach(this.arr, - item => { + (item: number) => { Child({ value: item }) }, - item => item.toString() // 键值,标识id + (item: string) => item.toString() // 键值,标识id ) Text('Parent: replace entire arr') .fontSize(50) diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md b/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md index ff15b61308f857dfa8e28bbbee475d30a2f4060c..d473dc4bb72720cbaa648e38ddbbc8b6b1e1e063 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @@ -202,7 +202,7 @@ class MyDataSource extends BasicDataSource { @Component struct MyComponent { aboutToAppear() { - for (var i = 100; i >= 80; i--) { + for (let i = 100; i >= 80; i--) { this.data.pushData(`Hello ${i}`) } } @@ -223,7 +223,7 @@ struct MyComponent { .onClick(() => { this.data.pushData(`Hello ${this.data.totalCount()}`); }) - }, item => item) + }, (item: string) => item) }.cachedCount(5) } } 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 2b43630dabee7a29420404f80c963cb8b99d08f7..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 @@ -41,7 +41,7 @@ struct LinkChild { @Component struct PropChild2 { - @Prop testNum: ClassA; + @Prop testNum: ClassA = new ClassA(0); build() { Text(`PropChild2 testNum ${this.testNum.c}`) @@ -53,7 +53,7 @@ struct PropChild2 { @Component struct PropChild3 { - @Prop testNum: ClassA; + @Prop testNum: ClassA = new ClassA(0); build() { Text(`PropChild3 testNum ${this.testNum.c}`) @@ -460,10 +460,10 @@ struct ParentComp { CounterComp({ value: this.counter[2] }) Divider().height(5) ForEach(this.counter, - item => { + (item: ParentCounter) => { CounterComp({ value: item }) }, - item => item.id.toString() + (item: ParentCounter) => item.id.toString() ) Divider().height(5) // 第一个点击事件 @@ -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也会进行正确的刷新。 @@ -576,10 +576,10 @@ struct ParentComp { CounterComp({ value: this.counter[2], subValue: this.counter[2].subCounter }) Divider().height(5) ForEach(this.counter, - item => { + (item: ParentCounter) => { CounterComp({ value: item, subValue: item.subCounter }) }, - item => item.id.toString() + (item: ParentCounter) => item.id.toString() ) Divider().height(5) Text('Parent: reset entire counter') @@ -673,10 +673,10 @@ struct ParentComp { CounterComp({ value: this.counter[2], subValue: this.counter[2].subCounter }) Divider().height(5) ForEach(this.counter, - item => { + (item: ParentCounter) => { CounterComp({ value: item, subValue: item.subCounter }) }, - item => item.id.toString() + (item: ParentCounter) => item.id.toString() ) Divider().height(5) Text('Parent: reset entire counter') @@ -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}`) @@ -754,6 +754,37 @@ struct CounterComp { ```ts +let nextId = 1; + +@Observed +class SubCounter { + counter: number; + constructor(c: number) { + this.counter = c; + } +} + +@Observed +class ParentCounter { + id: number; + counter: number; + subCounter: SubCounter; + incrCounter() { + this.counter++; + } + incrSubCounter(c: number) { + this.subCounter.counter += c; + } + setSubCounter(c: number): void { + this.subCounter.counter = c; + } + constructor(c: number) { + this.id = nextId++; + this.counter = c; + this.subCounter = new SubCounter(c); + } +} + @Component struct SubCounterComp { @ObjectLink subValue: SubCounter; @@ -767,7 +798,7 @@ struct SubCounterComp { } @Component struct CounterComp { - @Prop value: ParentCounter; + @ObjectLink value: ParentCounter; build() { Column({ space: 10 }) { Text(`this.value.incrCounter(): this.value.counter: ${this.value.counter}`) @@ -798,10 +829,10 @@ struct ParentComp { CounterComp({ value: this.counter[2] }) Divider().height(5) ForEach(this.counter, - item => { + (item: ParentCounter) => { CounterComp({ value: item }) }, - item => item.id.toString() + (item: ParentCounter) => item.id.toString() ) Divider().height(5) Text('Parent: reset entire counter') @@ -917,8 +948,8 @@ build函数中更改应用状态的行为可能会比上面的示例更加隐蔽 ```ts -@State arr : Array<..> = [ ... ]; -ForEach(this.arr.sort().filter(....), +@State arr : Array<...> = [ ... ]; +ForEach(this.arr.sort().filter(...), item => { ... }) @@ -928,7 +959,7 @@ ForEach(this.arr.sort().filter(....), ```ts -ForEach(this.arr.filter(....).sort(), +ForEach(this.arr.filter(...).sort(), item => { ... }) @@ -949,15 +980,18 @@ struct CompA { realState1: Array = [4, 1, 3, 2]; // 未使用状态变量装饰器 realState2: Color = Color.Yellow; - updateUI(param: any): any { + updateUI1(param: Array): Array { + const triggerAGet = this.needsUpdate; + return param; + } + updateUI2(param: Color): Color { const triggerAGet = this.needsUpdate; return param; } - build() { Column({ space: 20 }) { - ForEach(this.updateUI(this.realState1), - item => { + ForEach(this.updateUI1(this.realState1), + (item: Array) => { Text(`${item}`) }) Text("add item") @@ -976,7 +1010,7 @@ struct CompA { // 触发UI视图更新 this.needsUpdate = !this.needsUpdate; }) - }.backgroundColor(this.updateUI(this.realState2)) + }.backgroundColor(this.updateUI2(this.realState2)) .width(200).height(500) } } @@ -1005,7 +1039,7 @@ struct CompA { build() { Column({ space: 20 }) { ForEach(this.realState1, - item => { + (item: Array) => { Text(`${item}`) }) Text("add item") @@ -1108,7 +1142,7 @@ struct Parent { @Component struct Child { - @Prop voteOne: ClassE + @ObjectLink voteOne: ClassE build() { Column() { Text(this.voteOne.name).fontSize(24).fontColor(Color.Red).margin(50) @@ -1123,7 +1157,7 @@ struct Child { @Component struct ChildOne { - @Prop voteTwo: ClassD + @ObjectLink voteTwo: ClassD build() { Column() { Text(this.voteTwo.name).fontSize(24).fontColor(Color.Red).margin(50) @@ -1138,7 +1172,7 @@ struct ChildOne { @Component struct ChildTwo { - @Prop voteThree: ClassC + @ObjectLink voteThree: ClassC build() { Column() { Text(this.voteThree.name).fontSize(24).fontColor(Color.Red).margin(50) @@ -1153,7 +1187,7 @@ struct ChildTwo { @Component struct ChildThree { - @Prop voteFour: ClassB + @ObjectLink voteFour: ClassB build() { Column() { Text(this.voteFour.name).fontSize(24).fontColor(Color.Red).margin(50) @@ -1168,7 +1202,7 @@ struct ChildThree { @Component struct ChildFour { - @Prop voteFive: ClassA + @ObjectLink voteFive: ClassA build() { Column() { Text(this.voteFive.title).fontSize(24).fontColor(Color.Red).margin(50) @@ -1245,6 +1279,59 @@ class ClassE { 以下组件层次结构呈现的是@Reusable组件复用场景的数据结构。 ```ts +// 以下是嵌套类对象的数据结构。 +@Observed +class ClassA { + public title: string; + + constructor(title: string) { + this.title = title; + } +} + +@Observed +class ClassB { + public name: string; + public a: ClassA; + + constructor(name: string, a: ClassA) { + this.name = name; + this.a = a; + } +} + +@Observed +class ClassC { + public name: string; + public b: ClassB; + + constructor(name: string, b: ClassB) { + this.name = name; + this.b = b; + } +} + +@Observed +class ClassD { + public name: string; + public c: ClassC; + + constructor(name: string, c: ClassC) { + this.name = name; + this.c = c; + } +} + +@Observed +class ClassE { + public name: string; + public d: ClassD; + + constructor(name: string, d: ClassD) { + this.name = name; + this.d = d; + } +} @Entry @Component struct Parent { @@ -1266,9 +1353,9 @@ struct Parent { @Component struct Child { @State voteOne: ClassE = new ClassE('voteOne', new ClassD('OpenHarmony', new ClassC('Hello', new ClassB('World', new ClassA('Peace'))))) - aboutToReuse(params){ - this.voteOne = params + aboutToReuse(params: ClassE) { + this.voteOne = params } build() { Column() { @@ -1287,7 +1374,7 @@ struct Child { @Component struct ChildOne { @State voteTwo: ClassD = new ClassD('voteTwo', new ClassC('Hello', new ClassB('World', new ClassA('Peace')))) - aboutToReuse(params){ + aboutToReuse(params: ClassD){ this.voteTwo = params } build() { @@ -1307,7 +1394,7 @@ struct ChildOne { @Component struct ChildTwo { @State voteThree: ClassC = new ClassC('voteThree', new ClassB('World', new ClassA('Peace'))) - aboutToReuse(params){ + aboutToReuse(params: ClassC){ this.voteThree = params } @@ -1328,7 +1415,7 @@ struct ChildTwo { @Component struct ChildThree { @State voteFour: ClassB = new ClassB('voteFour', new ClassA('Peace')) - aboutToReuse(params){ + aboutToReuse(params: ClassB){ this.voteFour = params } @@ -1349,7 +1436,7 @@ struct ChildThree { @Component struct ChildFour { @State voteFive: ClassA = new ClassA('voteFive') - aboutToReuse(params){ + aboutToReuse(params: ClassA){ this.voteFive = params } 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/atomicService-aging.md b/zh-cn/application-dev/quick-start/atomicService-aging.md index c19291c7e2bfdcf43e752d3aa33bbefe820120ba..116a2feb1b77dae8a9d26965546c2c20e286d5a6 100644 --- a/zh-cn/application-dev/quick-start/atomicService-aging.md +++ b/zh-cn/application-dev/quick-start/atomicService-aging.md @@ -17,14 +17,15 @@ ```ts import installer from '@ohos.bundle.installer'; import { BusinessError } from '@ohos.base'; + let bundleName = 'com.ohos.demo'; let installParam: installer.InstallParam = { userId: 100 }; try { - installer.getBundleInstaller().then(data => { - data.uninstall(bundleName, installParam, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.uninstall(bundleName, installParam, (err: BusinessError) => { if (err) { console.error('uninstall failed:' + err.message); } else { diff --git a/zh-cn/application-dev/quick-start/har-package.md b/zh-cn/application-dev/quick-start/har-package.md index 0dbf9a34fd1f68a5a54f5a9297c27fe2a29302cb..991bb3b80f8fb7ee803002a9ef7dfcd3bcb815b8 100644 --- a/zh-cn/application-dev/quick-start/har-package.md +++ b/zh-cn/application-dev/quick-start/har-package.md @@ -75,7 +75,7 @@ index.ets文件是HAR导出声明文件的入口,HAR需要导出的接口, ``` ### 导出ArkUI组件 ArkUI组件的导出方式与ts的导出方式一致,通过`export`导出ArkUI组件,示例如下: -```js +```ts // library/src/main/ets/components/MainPage/MainPage.ets @Component export struct MainPage { @@ -94,13 +94,13 @@ export struct MainPage { } ``` HAR对外暴露的接口,在index.ets导出文件中声明如下所示: -```js +```ts // library/index.ets export { MainPage } from './src/main/ets/components/MainPage/MainPage' ``` ### 导出ts类和方法 通过`export`导出ts类和方法,支持导出多个ts类和方法,示例如下所示: -```js +```ts // library/src/main/ts/test.ets export class Log { static info(msg: string) { @@ -117,7 +117,7 @@ export function func2() { } ``` HAR对外暴露的接口,在index.ets导出文件中声明如下所示: -```js +```ts // library/index.ets export { Log } from './src/main/ts/test' export { func } from './src/main/ts/test' @@ -135,7 +135,7 @@ HAR模块编译打包时会把资源打包到HAR中。在编译构建HAP时,De ### 引用HAR的ArkUI组件 HAR的依赖配置成功后,可以引用HAR的ArkUI组件。ArkUI组件的导入方式与ts的导入方式一致,通过`import`引入HAR导出的ArkUI组件,示例如下所示: -```js +```ts // entry/src/main/ets/pages/index.ets import { MainPage } from "library" @@ -160,7 +160,7 @@ struct Index { ``` ### 引用HAR的类和方法 通过`import`引用HAR导出的ts类和方法,示例如下所示: -```js +```ts // entry/src/main/ets/pages/index.ets import { Log } from "library" import { func } from "library" @@ -186,7 +186,7 @@ struct Index { ``` ### 引用HAR的资源 通过`$r`引用HAR中的资源,例如在HAR模块的`src/main/resources`里添加字符串资源(在string.json中定义,name:hello_har)和图片资源(icon_har.png),然后在Entry模块中引用该字符串和图片资源的示例如下所示: -```js +```ts // entry/src/main/ets/pages/index.ets @Entry @Component 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/figures/Loading.png b/zh-cn/application-dev/reference/apis/figures/Loading.png new file mode 100644 index 0000000000000000000000000000000000000000..94deb45524ecc368edb9b62f3a07726465425420 Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/Loading.png differ diff --git a/zh-cn/application-dev/reference/apis/figures/Running.png b/zh-cn/application-dev/reference/apis/figures/Running.png new file mode 100644 index 0000000000000000000000000000000000000000..dc2f0addc47df3529113534145156e0888464a6d Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/Running.png differ diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 78726882de928a2b1d00ede2b2eae923851c87a4..5da1744f106dd33bb2fb081d6f507bfed0bb5511 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -7,7 +7,7 @@ ## 导入模块 -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl' ``` @@ -28,8 +28,8 @@ createAtManager(): AtManager **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); +```ts +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); ``` ## AtManager @@ -67,15 +67,16 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 try { - atManager.checkAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data) => { + atManager.checkAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -114,10 +115,12 @@ verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let data = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); +```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let data: abilityAccessCtrl.GrantStatus = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); console.log(`data->${JSON.stringify(data)}`); ``` @@ -161,16 +164,17 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags).then(() => { console.log('grantUserGrantedPermission success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -213,14 +217,15 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { - atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err, data) => { + atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err: BusinessError, data: void) => { if (err) { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -272,16 +277,17 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags).then(() => { console.log('revokeUserGrantedPermission success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -324,14 +330,15 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { - atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err, data) => { + atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err: BusinessError, data: void) => { if (err) { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -382,15 +389,16 @@ getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<num **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 try { - atManager.getPermissionFlags(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data) => { + atManager.getPermissionFlags(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: number) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`getPermissionFlags fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -416,10 +424,12 @@ getVersion(): Promise<number> **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); +```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); let promise = atManager.getVersion(); -promise.then(data => { +promise.then((data: number) => { console.log(`promise: data->${JSON.stringify(data)}`); }); ``` @@ -463,16 +473,16 @@ on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionLi **示例:** -```js -import {Permissions} from '@ohos.abilityAccessCtrl'; +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import bundleManager from '@ohos.bundle.bundleManager'; -let atManager = abilityAccessCtrl.createAtManager(); -let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let appInfo: bundleManager.ApplicationInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; let permissionList: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; try { - atManager.on('permissionStateChange', tokenIDList, permissionList, (data) => { + atManager.on('permissionStateChange', tokenIDList, permissionList, (data: abilityAccessCtrl.PermissionStateChangeInfo) => { console.debug('receive permission state change, data:' + JSON.stringify(data)); }); } catch(err) { @@ -516,12 +526,12 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionL **示例:** -```js -import {Permissions} from '@ohos.abilityAccessCtrl'; +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import bundleManager from '@ohos.bundle.bundleManager'; -let atManager = abilityAccessCtrl.createAtManager(); -let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let appInfo: bundleManager.ApplicationInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; let permissionList: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; try { @@ -558,15 +568,22 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<Gran **示例:** -```js -import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let promise = atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; +try { + atManager.verifyAccessToken(tokenID, permissionName).then((data: abilityAccessCtrl.GrantStatus) => { + console.log(`promise: data->${JSON.stringify(data)}`); + }).catch((err: BusinessError) => { + console.log(`verifyAccessToken fail, err->${JSON.stringify(err)}`); + }); +}catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### requestPermissionsFromUser9+ @@ -600,19 +617,68 @@ requestPermissionsFromUser(context: Context, permissionList: Array<Permission **示例:** - ```js +ArkTS语法不支持直接使用globalThis,需要通过一个单例的map来做中转。开发者需要: + + a. 在EntryAbility.ets中导入构建的单例对象GlobalThis。 + ```ts + import { GlobalThis } from '../utils/globalThis'; // 需要根据globalThis.ets的路径自行适配 + ``` + b. 在onCreate中添加: + ```ts + GlobalThis.getInstance().setContext('context', this.context); + ``` + + > **说明:** + > + > 由于在ts中引入ets文件会有告警提示,需要将EntryAbility.ts的文件后缀修改为EntryAbility.ets,并在module.json5中同步修改。 + +**globalThis.ets示例代码如下:** +```ts +import common from '@ohos.app.ability.common'; + +// 构造单例对象 +export class GlobalThis { + private constructor() {} + private static instance: GlobalThis; + private _uiContexts = new Map(); + + public static getInstance(): GlobalThis { + if (!GlobalThis.instance) { + GlobalThis.instance = new GlobalThis(); + } + return GlobalThis.instance; + } + + getContext(key: string): common.UIAbilityContext | undefined { + return this._uiContexts.get(key); + } + + setContext(key: string, value: common.UIAbilityContext): void { + this._uiContexts.set(key, value); + } + + // 其他需要传递的内容依此扩展 +} +``` + +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let atManager = abilityAccessCtrl.createAtManager(); +import { BusinessError } from '@ohos.base'; +import common from '@ohos.app.ability.common'; +import { GlobalThis } from '../utils/globalThis'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ['ohos.permission.CAMERA'], (err, data)=>{ - console.info('data:' + JSON.stringify(data)); - console.info('data permissions:' + data.permissions); - console.info('data authResults:' + data.authResults); + let context: common.UIAbilityContext = GlobalThis.getInstance().getContext('context'); + atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data)=>{ + console.info('data:' + JSON.stringify(data)); + console.info('data permissions:' + data.permissions); + console.info('data authResults:' + data.authResults); }); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } - ``` +``` ### requestPermissionsFromUser9+ @@ -651,21 +717,28 @@ requestPermissionsFromUser(context: Context, permissionList: Array<Permission **示例:** - ```js +修改EntryAbility.ets和导入GlobalThis等步骤同上,此处不再重复 + +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let atManager = abilityAccessCtrl.createAtManager(); +import { BusinessError } from '@ohos.base'; +import common from '@ohos.app.ability.common'; +import { GlobalThis } from '../utils/globalThis'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ['ohos.permission.CAMERA']).then((data) => { + let context: common.UIAbilityContext = GlobalThis.getInstance().getContext('context'); + atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA']).then((data) => { console.info('data:' + JSON.stringify(data)); console.info('data permissions:' + data.permissions); console.info('data authResults:' + data.authResults); - }).catch((err) => { + }).catch((err: BusinessError) => { console.info('data:' + JSON.stringify(err)); }) } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } - ``` +``` ### verifyAccessToken(deprecated) @@ -694,15 +767,21 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let promise = atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +try { + atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => { + console.log(`promise: data->${JSON.stringify(data)}`); + }).catch((err: BusinessError) => { + console.log(`verifyAccessToken fail, err->${JSON.stringify(err)}`); + }); +}catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### checkAccessTokenSync10+ @@ -736,10 +815,13 @@ checkAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus; **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let data = atManager.checkAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; +let data: abilityAccessCtrl.GrantStatus = atManager.checkAccessTokenSync(tokenID, permissionName); console.log(`data->${JSON.stringify(data)}`); ``` 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-app-ability-driverExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-driverExtensionAbility.md index 80fefa326bdcf8ea6b529cb73a689fb23f068139..b0bac4f898f3d52087cccea41f8fd5741eb9365e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-driverExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-driverExtensionAbility.md @@ -45,7 +45,7 @@ Extension生命周期回调,在创建时回调,执行初始化业务逻辑 ```ts class DriverExt extends DriverExtension { - onInit(want) { + onInit(want : Want) { console.log('onInit, want: ${want.abilityName}'); } } @@ -96,14 +96,14 @@ Extension生命周期回调,如果是connectAbility拉起的服务,会在onC ```ts import rpc from '@ohos.rpc'; class StubTest extends rpc.RemoteObject{ - constructor(des) { + constructor(des : string) { super(des); } - onRemoteMessageRequest(code, data, reply, option) { + onRemoteMessageRequest(code : number, data : MessageSequence, reply : MessageSequence, option : MessageOption) { } } class DriverExt extends DriverExtension { - onConnect(want) { + onConnect(want : Want) { console.log('onConnect , want: ${want.abilityName}'); return new StubTest('test'); } @@ -115,10 +115,10 @@ Extension生命周期回调,如果是connectAbility拉起的服务,会在onC ```ts import rpc from '@ohos.rpc'; class StubTest extends rpc.RemoteObject{ - constructor(des) { + constructor(des : string) { super(des); } - onRemoteMessageRequest(code, data, reply, option) { + onRemoteMessageRequest(code : number, data : MessageSequence, reply : MessageSequence, option : MessageOption) { } } async function getDescriptor() { @@ -126,7 +126,7 @@ async function getDescriptor() { return "asyncTest" } class DriverExt extends DriverExtension { - async onConnect(want) { + async onConnect(want : Want) { console.log(`onConnect , want: ${want.abilityName}`); let descriptor = await getDescriptor(); return new StubTest(descriptor); @@ -152,7 +152,7 @@ Extension的生命周期回调,客户端执行断开连接服务时回调。 ```ts class DriverExt extends DriverExtension { - onDisconnect(want) { + onDisconnect(want : Want) { console.log('onDisconnect, want: ${want.abilityName}'); } } @@ -162,7 +162,7 @@ Extension的生命周期回调,客户端执行断开连接服务时回调。 ```ts class DriverExt extends DriverExtension { - async onDisconnect(want) { + async onDisconnect(want : Want) { console.log('onDisconnect, want: ${want.abilityName}'); // 调用异步函数... } @@ -188,7 +188,7 @@ onDump(params: Array\): Array\; ```ts class DriverExt extends DriverExtension { - onDump(params) { + onDump(params : Array) { console.log('dump, params: ${JSON.stringify(params)}'); return ['params']; } diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md index ac87434396b5973f3e83146401f75400b081715d..c0ca0c0afabbe875aba613add5e9b94510a36ba0 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -1300,7 +1300,7 @@ moveMissionToFront(missionId: number, options?: StartOptions): Promise<void&g | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | missionId | number | 是 | 任务ID。 | - | options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动参数选项,用于指定任务切到前台时的窗口模式,设备ID等。 | + | options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动参数选项,用于指定任务切到前台时的窗口模式,设备ID等。默认为空,表示按照默认启动参数。 | **返回值:** @@ -1484,7 +1484,7 @@ moveMissionsToForeground(missionIds: Array<number>, topMission?: number): | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | missionIds | Array<number> | 是 | 任务ID数组。 | - | topMission | number | 否 | 待移动到最顶层的任务ID | + | topMission | number | 否 | 待移动到最顶层的任务ID。默认值为-1,表示将默认任务移动到最顶层。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md index ea086e8f5f5c8587372f655f002c75654ae7d225..005e6cb411c81a96ec4b68cb7b1f151900782c69 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md @@ -74,7 +74,7 @@ loadContent(path: string, storage?: LocalStorage): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | +| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。默认为空。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md index dd8f03d8d7edc690cf5ecb68ebcdf8a3db95050a..3929632886844574e65e673b441be97b715edb46 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md @@ -160,7 +160,7 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | ----------- | | formId | string | 是 | 卡片标识。 | -| isReleaseCache | boolean | 否 | 是否释放缓存。 | +| isReleaseCache | boolean | 否 | 是否释放缓存,默认为false。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md index a977546199a950cafb414d64a6fad24a5713480d..f26f7ed912fc87047d0e6c6488954bcedd18608a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md @@ -41,12 +41,13 @@ onConnect(want: Want): void **示例:** ```ts -export default class MyWindowExtensionAbility extends WindowExtensionAbility { +import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; +import Want from '@ohos.app.ability.Want'; - onConnect(want) { +export default class MyWindowExtensionAbility extends WindowExtensionAbility { + onConnect(want: Want) { console.info('WindowExtAbility onConnect, abilityName: ${want.abilityName}'); } - } ``` @@ -68,12 +69,13 @@ onDisconnect(want: Want): void **示例:** ```ts -export default class MyWindowExtensionAbility extends WindowExtensionAbility { +import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; +import Want from '@ohos.app.ability.Want'; - onDisconnect(want) { +export default class MyWindowExtensionAbility extends WindowExtensionAbility { + onDisconnect(want: Want) { console.info('WindowExtAbility onDisconnect, abilityName: ${want.abilityName}'); } - } ``` @@ -95,16 +97,20 @@ onWindowReady(window: window.Window): void **示例:** ```ts +import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; +import window from '@ohos.window'; + +let windowStage: window.WindowStage | null = null + export default class MyWindowExtensionAbility extends WindowExtensionAbility { + onWindowReady(windowClass: window.Window) { - onWindowReady(window) { - window.loadContent('WindowExtAbility/pages/index1').then(() => { - window.getProperties().then((pro) => { + windowStage!.loadContent('WindowExtAbility/pages/index1').then(() => { + windowClass.getProperties().then((pro: window.WindowProperties) => { console.log('WindowExtension pro: ${JSON.stringify(pro)}'); }); - window.show(); + windowClass.show(); }); } - } ``` \ No newline at end of file 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 7934d668789cbe0010c6a824a25316b3ca062d90..73bbc4b1cdce7f0e42149b54ac58204e29a301f6 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.unifiedDataChannel'; @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) { // ... } }) @@ -107,7 +112,7 @@ executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: DragInfo): Promise&l import dragController from "@ohos.arkui.dragController" import componentSnapshot from '@ohos.arkui.componentSnapshot'; import image from '@ohos.multimedia.image'; -import UDC from '@ohos.data.unifiedDataChannel'; +import UDMF from '@ohos.data.unifiedDataChannel'; @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-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index eaff3e7155873d448913a4442093a304267d0f2b..bd51282cd1e8c2a3316a1e97820fb1007d9110e2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -14,7 +14,7 @@ ## 导入模块 -```js +```ts import audio from '@ohos.multimedia.audio'; ``` @@ -28,7 +28,7 @@ import audio from '@ohos.multimedia.audio'; **示例:** -```js +```ts import audio from '@ohos.multimedia.audio'; const localNetworkId = audio.LOCAL_NETWORK_ID; @@ -51,8 +51,8 @@ getAudioManager(): AudioManager | [AudioManager](#audiomanager) | 音频管理类。 | **示例:** -```js -let audioManager = audio.getAudioManager(); +```ts +let audioManager: audio.AudioManager = audio.getAudioManager(); ``` ## audio.createAudioRenderer8+ @@ -72,24 +72,24 @@ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\ **示例:** -```js +```ts import fs from '@ohos.file.fs'; import audio from '@ohos.multimedia.audio'; +import { BusinessError } from '@ohos.base'; -let audioStreamInfo = { +let audioStreamInfo: audio.AudioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } -let audioRendererInfo = { +let audioRendererInfo: audio.AudioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, rendererFlags: 0 } -let audioRendererOptions = { +let audioRendererOptions: audio.AudioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo } -let audioRenderer; +let audioRenderer: audio.AudioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ${err}`); }); ``` @@ -176,21 +177,21 @@ createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback